Vue自定义指令实现元素根据权限进行渲染

313 阅读1分钟
permission.js

const roleList = ['/list', '/detail']
function checkPermission(el, binding, vnode) {
  const { value } = binding
  if (value) {
    const hasPms = codeList.includes(value)
    // 如果不匹配
    if(!(hasPms)){
      // 创建一个注释元素
      const comment = document.createComment(' ')
      // 设置value值
      Object.defineProperty(comment, 'setAttribute', { value: () =>  undefined })
      // 用注释节点替换 当前页面元素
      vnode.elm = comment;
      // 下面作为初始化操作 赋值为空
        vnode.text = ' ';
        vnode.isComment = true;
        vnode.context = undefined;
        vnode.tag = undefined;
        vnode.data.directives = undefined;

        // 判断当前元素是否是组件  如果是组件的话也替换成 注释元素
        if (vnode.componentInstance) {
        vnode.componentInstance.$el = comment;
        }

        // 判断当前元素是否是文档节点或者是文档碎片节点
        if (el.parentNode) {
        // 从 DOM 树中删除 node 节点,除非它已经被删除了。
        el.parentNode.replaceChild(comment, el);
      }
    }

  } else {
    throw new Error(`v-permission="/list"`)
  }
}

export default {
  inserted(el, binding, vnode) {
    checkPermission(el, binding, vnode)
  },
  // 如果不涉及类似tab这种切换,不需要update
  update(el, binding, vnode) {
    checkPermission(el, binding, vnode)
  }
}





index.js

import permission from './permission'
const install = function(Vue) {
  Vue.directive('permission', permission)
}
if (window.Vue) {
  window['permission'] = permission
  Vue.use(install);
}
permission.install = install
export default permission




main.js-全局自定义指令

import permission from '@/directive/permission/index.js'
Vue.use(permission)




temp.vue
<template>
    <span v-permission="/list">当前已登录的人员是否有该权限显示</span>
</template>