Skip to content

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

Open
Open
@mu-muw

Description

@mu-muw
// 你的答案
<script setup>

import { ref, watchEffect } from "vue"

/**
* 实现该指令 :
* 当切换该选项卡时,列表项文本颜色变为红色
* 
*/
const VActiveStyle = {
  //el 当前组件的根元素,{value} 是一个对象
  mounted(el, { value }) {
    const [sty, z] = value
    console.log(sty, z)
    watchEffect(() => {
      // 使用 Object.keys 获取 styles 对象的所有键
      Object.keys(sty).forEach(key => {
        // 将每个键对应的值应用到元素的样式上
        el.style[key] = z() ? sty[key] : ''
      })
    })
  }
}

const list = [1, 2, 3, 4, 5, 6, 7, 8]
const activeTab = ref(0)
function toggleTab(index) {
  console.log(index)
  activeTab.value = index
}

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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions