自定义指令
在vue.js官网的 可复用性&组合 里面的自定义属性
v-permission
权限控制,使用自定义属性代替 v-if与v-show
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>
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)