vue自定义指令

2021-04-25  本文已影响0人  A_dfa4

呔, 用了俩年vue 竟然没怎么用过自定义指令, 面试问到了就找个几个常用的
实现按钮权限的自定义指令 v-permission="code"

Vue.directive("permission", {
  inserted(el, binding) {
    let { value } = binding
    let res = roleList.some((it) => {
      return it && it == value
    })
    if (!res) {
      el.style.display = 'none'
    }
  }
})

<div style="width: 200px;">
   <el-input v-model="input" placeholder="请输入内容" v-focus v-permission="7"></el-input>
   <el-button type="info" v-permission="5">权限按钮</el-button>
</div>

防止按钮频繁被点击的自定义指令 v-preventReClick="time"

Vue.directive("preventReClick", {
      inserted(el, binding) {
          el.addEventListener("click", () => {
              if (!el.disabled) {
                  el.disabled = true;
                  setTimeout(() => {
                      el.disabled = false;
                  }, binding.value || 1000);
              }
          });
      }
  });

<el-button type="primary" v-preventReClick="5000" @click="test">主要按钮</el-button>

input自动聚焦的自定义指令 v-focus

Vue.directive('focus', {
    inserted: function (el,  binding) {
      let input = el.querySelector("input"); 
      input.focus()
    }
})

<el-input v-model="input" placeholder="请输入内容" v-focus ></el-input>
批量注册自定义指令
import copy from './v-copy';
// 自定义指令
const directives = {
  copy,
};
// 这种写法可以批量注册指令
export default {
  install(Vue) {
    Object.keys(directives).forEach((key) => {
      Vue.directive(key, directives[key]);
    });
  },
};
上一篇 下一篇

猜你喜欢

热点阅读