vuejs-challenges icon indicating copy to clipboard operation
vuejs-challenges copied to clipboard

24 - 激活的样式-指令

Open kalu5 opened this issue 2 years ago • 0 comments

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

import { ref, watchEffect, Binding, unref } 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: HTMLLiElment, binding: Binding) {
    const [ cssObj, fn ] = binding.value;
    watchEffect(() => {
       if (fn && fn()) {
          Object.keys(cssObj).forEach(key => {
            el.style[key] = unref(cssObj[key])
          })
       } else {
         Object.keys(cssObj).forEach(key => {
           el.style[key] = ''
         })
       }
    })
  }
}

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>

kalu5 avatar Sep 19 '22 06:09 kalu5