webfansplz / vuejs-challenges

Collection of Vue.js challenges
https://vuejs-challenges.netlify.app/
MIT License
2.7k stars 188 forks source link

24 - 激活的样式-指令 #2677

Open c11ee opened 4 months ago

c11ee commented 4 months ago
<script setup lang="ts">
import { effectScope, ref, watchEffect, type Directive } from 'vue'

const scope = effectScope()
/**
 * 实现该指令 :
 * 当切换该选项卡时,列表项文本颜色变为红色
 *
 */
const VActiveStyle: Directive<HTMLLIElement, [CSSStyleDeclaration, () => boolean]> = {
  mounted: (el, { value }) => {
    scope.run(() => {
      watchEffect(() => {
        const [style, fn] = value
        const active = fn()

        for (const classKey in style) {
          el.style[classKey] = active ? style.color : ''
        }
      })
    })
  }
}

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>