zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    關于招聘新人
    JS在线打字练习 PHP
    useragent 分析 PHP
    webSql工具 PHP
    《网站开发人员应该知道的61件事》[解读] PHP
    HTMLCSS速查 PHP
    Flash文字转图片 PHP
    Flash简易文件上传 PHP
    Google 字体 API PHP
    Google 二维条码 API PHP
  • 原文地址:https://www.cnblogs.com/wuqilang/p/15109420.html
Copyright © 2011-2022 走看看