vue自定义指令

批量注册指令:新建auth.js文件

import Vue from 'vue';
const remove = (el) => el.parentNode.removeChild(el);
Vue.directive('auth',{
  inserted: (el,binding,vNode) => {
    const {$root:vm} = vNode.context;
    const auths = vm.$store.state.auths;
    if (auths.includes(binding.value) {
      return true
    }else {
      remove(el)
    }
  }
})

新建 directives/index.js 文件

import auth from './auth'
import longpress from './longpress'
import Vue from 'vue' // 自定义指令 const directives = { auth, longpress, } export default { install(Vue) { Object.keys(directives).forEach((key) => { Vue.directive(key, directives[key]) }) }, }

在 main.js 引入并调用

import Vue from 'vue'
import Directives from './JS/directives'
Vue.use(Directives)

 拓展:使用iview等控件时,会发现类型表格之类的组件不是写在template标签里的,而是用createElement的形式。这时候可以在h属性里的和props、class同级的地方写上 directives:[{name:'auth',value:'home-select'}] 即可实现v-auth = "'home-select'"的效果了

 

官方文档:https://cn.vuejs.org/v2/guide/custom-directive.html#ad

使用介绍博客:https://blog.csdn.net/smlljet/article/details/91874728

8个非常常用的 Vue自定义指令:https://www.jb51.net/article/202156.html

15个vue自定义指令:https://blog.csdn.net/weixin_39622332/article/details/111164381

 

2022.01.18更新:将自定义指令绑定在根标签template底下的div底下的标签button上,同级的标签template有一个v-for="item in list",这个list是从后台获取数据后填充的。发现没有权限删除el时会导致同级的标签template(带v-for的这个)整个都不显示了。我尝试将带button标签移到同级的template标签上方,发现就可以显示了。或者在顶级template底下的div标签上加个v-if="!isEmpty(list)"也可以避免这个问题。或者在自定义指令里用display:none代替removeChild也可以。 debugger发现页面开始渲染时先加载了button,后续才加载同级的template,猜测是这个原因,具体的还需要进一步研究。

2021.01.20更新:已经提交了issue到vue的github,得到回复是我不应该删除带有vue指令的元素,因为这个元素应该要被vue虚拟dom所控制。

总结:以后写自定义指令控制显示隐藏,就直接用display:none来控制吧

posted @ 2021-11-19 17:58  太阳锅锅  阅读(178)  评论(0编辑  收藏  举报