vue自定义指令

自定义一个TabBar组件:

<template>
  <div class="tab-bar">
    <div v-for="(item,index) in tabList" :key="index" :class="['common',{active:currentIndex===index}]" @click="currentIndex=index">{{item}}</div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      tabList: ['项目一', '项目二', '项目三'],
      currentIndex: 0
    }
  }
}
</script>
<style lang='less' scoped>
.tab-bar {
  display: flex;
  .common {
    width: 100px;
    line-height: 36px;
    text-align: center;
    border: 1px solid #000;
    cursor: pointer;
  }
  .active {
    background-color: red;
  }
}
</style>

通过动态绑定类名(active)实现点击高亮。

 

封装成指令:

1、src/directives/navActive.js:

export default {
  bind: (el, binding) => {
    // 设置初始化高亮类名
    const { className, activeClass, currentIndex } = binding.value
    const children = el.getElementsByClassName(className)
    children[currentIndex].className += ` ${activeClass}`
  },
  update: (el, binding) => {
    // 设置被点击tab的高亮类名,并清除之前的tab的高亮类名
    const { className, activeClass, currentIndex } = binding.value
    const children = el.getElementsByClassName(className)
    children[currentIndex].className += ` ${activeClass}`
    const { currentIndex: oldIndex } = binding.oldValue
    children[oldIndex].className = className
  }
}

2、使用

  引入指令并注册指令:

import NavActive from '@/directives/navActive'
  directives: { NavActive }

  使用指令,并传入对应的参数给指令:(class只需要写common就行了)

  <div class="tab-bar" v-NavActive="{className:'common',activeClass:'active',currentIndex}">
    <div v-for="(item,index) in tabList" :key="index" class='common' @click="currentIndex=index">{{item}}</div>
  </div>

 

上一篇:vue_点击列表项变色(结合v-for和v-bind来实现)


下一篇:iOS短视频app搭建,仿抖音的上下滑实现