美文网首页
Vue自定义指令,封装自定义指令

Vue自定义指令,封装自定义指令

作者: 残_忆 | 来源:发表于2020-04-28 17:19 被阅读0次

自定义指令

Vue.directive('authority', {
  // 当被绑定的元素插入到 DOM 中时……
  inserted: function (el, binding, vnode) {
    const { value } = binding
    const roles = localStorage.getItem("userType");
  
    if (value && value instanceof Array && value.length > 0) {
      const permissionRoles = value
  
      const hasPermission = permissionRoles.some(item => {
        return roles.includes(item)
      })
  
      if (!hasPermission) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    } else {
      throw new Error(`v-authority`)
    }
  }
})

自定义指令封装
directives.js文件存放所有自定义指令

const authority = {
  inserted : function (el, binding, vnode) {
    console.log(el)
    const { value } = binding
    const roles = localStorage.getItem("userType");
  
    if (value && value instanceof Array && value.length > 0) {
      const permissionRoles = value
  
      const hasPermission = permissionRoles.some(item => {
        return roles.includes(item)
      })
  
      if (!hasPermission) {
        console.log(el.parentNode)
        el.parentNode && el.parentNode.removeChild(el)
      }
    } else {
      throw new Error(`v-authority`)
    }
  }
}


export default{
  authority:authority,
}

main.js中引用

import directives from './directive/directives.js' //

Object.keys(directives).forEach((key)=>{
  Vue.directive(key,directives[key])
})

相关文章

网友评论

      本文标题:Vue自定义指令,封装自定义指令

      本文链接:https://www.haomeiwen.com/subject/kqenwhtx.html