自定义指令
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])
})
网友评论