Vue 权限控制 使用自定义指令 代替v-if

参考了vue-element-admin 指令库的permission

使用Demo(demo.vue)

<template>
  <p>admin组:<span v-permission="['admin']">可看见v-permission="['admin']"</span></p>
  
  <p>editor:<span v-permission="['editor']">可看见v-permission="['editor']"</span></p>
  
  <p>admin editor组:<span v-permission="['admin','editor']">可看见v-permission="['admin','editor']"</span></p>
  
  <p>another组:<span v-permission="['another']">可看见v-permission="['another']"</span></p>
</template>

v-permission指令代码 注册到全局(main.js)

const permission={
    inserted(el, binding, vnode) {
        const { value } = binding
        const roles = ['editor','admin']
        if (value && value instanceof Array && value.length > 0) {
            const permissionRoles = value
            const hasPermission = roles.some(role => {
                return permissionRoles.includes(role)
            })
            if (!hasPermission) {
                el.parentNode && el.parentNode.removeChild(el)
            }
        } else {
            throw new Error(`need roles! Like v-permission="['admin','editor']"`)
        }
    }
}

Vue.directive('permission', permission)

对比

-  v-show (v-show的dom不隐藏,改变display用户可以看到不该看的信息)

- v-if (v-if删除节点遗留<!-- -->的注释)

易维护,明了

posted @ 2019-10-09 00:26  润润润  阅读(12104)  评论(2编辑  收藏  举报