Skip to content

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

Open
Open
@landejin

Description

@landejin

注意点:

  • 参数一是对象,应该进行遍历设置激活样式
  • 激活前,可能设置了和激活效果冲突的style,在取消激活状态时应该还原初始的style,因此应该在 mounted 生命周期中进行样式设置,否则初始激活设置的样式,可能被style覆盖
<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, binding) => {
    const [style, getActive] = binding.value
    const prevStyle = {}
    
    const setActive = () => {
      Object.keys(style).forEach(_style => {
        prevStyle[_style] = el.style[_style] // 记录激活前的对应样式
        el.style[_style] = style[_style] // 设置激活的样式
      })
    }
    
    watch(getActive, (val) => {
      if (val) {
        setActive()
      } else { // 非激活状态,还原激活前的样式
        Object.keys(style).forEach(_style => {
          el.style[_style] = prevStyle[_style] // 设置激活的样式
        })
      }
    }, {
      immediate: true
    })
  },
}

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>
    
    <br />
    
    <li
      v-for="(item,index) in list"
      :key="index"
      style="color: blue"
      v-active-style="[{'color':'red'},() => activeTab === index]"
      @click="toggleTab(index)"
    >
      {{ item + 8 }}
    </li>
  </ul>
</template>

Vue SFC Playground 在线链接

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions