Skip to content

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

Open
@JarhsonNing

Description

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

import { ref, computed, watch, watchEffect } 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 initStyle = {}
    const [style, isActiveFn] = binding.value;
    const isActive = computed(() => isActiveFn());
    watchEffect(() => {
      if (isActive.value) {
        Object.keys(style).forEach(key => {
          initStyle[key] = el.style[key]
					el.style[key] = style[key]
        })
      } else {
        Object.keys(initStyle).forEach(key => {
					el.style[key] = initStyle[key]
        })
      }
    })
  }
}

const list = [1, 2, 3, 4, 5, 6, 7, 8]
const activeTab = ref(2)
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 }}1
    </li>
  </ul>
</template>

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @JarhsonNing

        Issue actions

          24 - 激活的样式-指令 · Issue #969 · webfansplz/vuejs-challenges