webfansplz / vuejs-challenges

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

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

Open XiaSean opened 3 months ago

XiaSean commented 3 months ago

// 你的答案
<script setup lang='ts'>

import { ref, watch } 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: HTMLLIElement, binding: any) {
    const [style, getActive] = binding.value
    watch(activeTab, () => {
      el.style.color = getActive() ? 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>