自定义指令实现tab选项卡切换

<template>
  <div class="home">
    <!-- 简单tab -->
    <!-- .active_s -->
    <div
      id="tab"
      v-cTab="{
        activeIndex,
        activeName: 'active_s'
      }"
    >
      <span
        v-for="(item, index) in list"
        :key="index"
        @click="activeIndex = index"
        >{{ item.value }}</span
      >
    </div>
  </div>
</template>
<script>
import tab from '../components/tab/tab.vue'
import btnMix from '../libs/myui/mix.js'
export default {
  name: 'Home',
  // 这是一种局部的混合
  // mixins: [btnMix],
  components: { tab },
  data() {
    return {
      list: [
        {
          value: '选1'
        },
        { value: '选2' },
        { value: '选3' }
      ],
      activeIndex: 0 // 默认激活
    }
  },
  directives: {
    cTab: {
      bind(el, binds, vnode) {
        const spans = el.getElementsByTagName('span')
        // console.log(spans)
        const index = binds.value.activeIndex
        spans[index].className = `${binds.value.activeName}`
      },
      update(el, binds, vnode) {
        const spans = el.getElementsByTagName('span')
        const index = binds.value.activeIndex
        // 获取到旧的
        const oldIndex = binds.oldValue.activeIndex
        spans[oldIndex].className = ''
        spans[index].className = `${binds.value.activeName}`
      }
    }
  }
}
</script>
<style type="text/css">
#tab span {
  display: inline-block;
  width: 50px;
  height: 20px;
  border: 1px solid black;
  cursor: pointer;
}
#tab .active_s {
  background-color: blue;
  color: white;
}
</style>

1.bind 和update相当于两个实际
前者是绑定的时候 后者是数据更新的时候
2.binding里面保存着参数
在切换的时候可以使用oldValue拿到更新前的旧数据 ,重置类名
3.el是自定义指令使用的那个dom元素

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值