Skip to content

24 - v-active-style #1003

Open
Open
@HongxuanG

Description

@HongxuanG
// your answers
<script setup lang="ts">
import { ref, watchEffect, computed } from 'vue';

/**
 * Implement the custom directive
 * Make sure the list item text color changes to red when the `toggleTab` is toggled
 *
 */
const VActiveStyle = {
  // 在绑定元素的父组件
  // 及他自己的所有子节点都挂载完成后调用
  mounted(el, binding, vnode, prevVnode) {
    let [styleObj, callback] = binding.value;
    const isActive = computed(() => callback());
    watchEffect(() => {
      Object.keys(styleObj).map((styleKey) => {
        el.style[styleKey] = isActive.value ? styleObj[styleKey] : '';
      });
    });
  },
};

const list = [1, 2, 3, 4, 5, 6, 7, 8];
const activeTab = ref(0);
function toggleTab(index: number) {
  activeTab.value = index;
}
</script>

<template>
  <ul>
    <li
      v-for="(item, index) in list"
      :key="index"
      v-active-style="[{ color: 'red' }, () => activeTab === index]"
      @click="toggleTab(index)"
    >
      {{ item }}
    </li>
  </ul>
</template>

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @HongxuanG

        Issue actions

          24 - v-active-style · Issue #1003 · webfansplz/vuejs-challenges