vue自定义指令

自定义指令在开发过程中会用到 官方文档也有介绍这里
这里就展示一个自定义指令的使用
还是以切换选项卡来展示

原来的切换是这么写的

<div
        v-for="(item,index) in items"
        :key="index"
        @click="changeIndex(index)"
        :class="['nav-item',{'nav-active': index == currentIndex}]"
      >{{item}}</div>
items: ["项目1", "项目2", "项目3"],
      currentIndex: 0,

接着引用自定义指令

import index from "./index";
// 注册指令
  directives: {
    index,
  },

这里是index.js文件的代码

export default {
    bind: function (el, binding) {
        const options = binding.value
        const {
            className,
            activeClassName,
            currentIndex
        } = options
        const children = el.getElementsByClassName(className)
        console.log(children)
        children[currentIndex].className += ` ${activeClassName}`
    },
    update: function (el, binding) {
        const options = binding.value

        const oldOptions = binding.oldValue
        const {
            className,
            activeClassName,
            currentIndex
        } = options
        const children = el.getElementsByClassName(className)
        const {
            currentIndex: oldCurrentIndex
        } = oldOptions
        children[currentIndex].className += ` ${activeClassName}`
        children[oldCurrentIndex].className = className
    }
}

于是就可以这么写

    <div
      v-index="{
      className: 'nav-item',
      activeClassName: 'nav-active',
      currentIndex
    }"
    >
      <div
        v-for="(item,index) in items"
        :key="index"
        @click="changeIndex(index)"
        class="nav-item"
      >{{item}}</div>
    </div>

这样就完成了自定义指令 v-index
这样做的好处是 代码有了更高的复用性 之后别的文件需要这个切换方法只需引用 绑定好className 就可以实现切换效果
代码很简单主要是自己记录一下自定义指令的使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值