Skip to content

24 - v-active-style #2131

Open
Open
@alirezamou

Description

@alirezamou
<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 render = function () {
    for(const property in this.activeStyle) {
      this.$element.style[property] = this.isActive?.() ? this.activeStyle[property] : '';
    }
}

const VActiveStyle = {
  mounted: ($element, { value }) => {
    if(!Array.isArray(value)) {
      throw new Error('[VActiveStyle] : value must be an array');
    }
    const activeStyle = value.at(0);
    const isActive = value.at(1);
    watch(isActive, () => {
      render.call({activeStyle, isActive, $element});
    }, {
      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', 'font-weight': 'bold'},() => 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