需要做按钮的权限控制时可用到
首先需要后台验证登录以后的页面接受后台传的指令集
给它塞到localStorage 或者 sessionStorage里
写一个全局方法用来验证
/*
authName==>权限名称
userAuthList==>用户权限集
hasAuth==>验证结果
*/
export function checkAuth(authName, userAuthList) {
let hasAuth = true;
if (authName) {
//判断是否是数组。有时候权限需要多重支持 以['权限1','权限2'] 格式的也可以被认证
if (authName instanceof Array && authName.length > 0) {
hasAuth = userAuthList.some(it =>
//includes:查找
authName.includes(it)
);
} else {
hasAuth = userAuthList.some(item => item === authName);
}
}
return hasAuth;
}
/*
.some()
some() 方法用于检测数组中的元素是否满足指定条件(函数提供)。
some() 方法会依次执行数组的每个元素:
如果有一个元素满足条件,则表达式返回true , 剩余的元素不会再执行检测。
如果没有满足条件的元素,则返回false。
注意: some() 不会对空数组进行检测。
注意: some() 不会改变原始数组
*/
写一个自定义指令
import { checkAuth } from "./Auth";
export default {
/**
* 自定义指令
* @param {*} el 指令所绑定的元素,可以用来直接操作 DOM。
* @param {*} binding binding:一个对象,包含以下 property:
name:指令名,不包括 v- 前缀。
value:指令的绑定值,例如:v-my-directive="1 + 1" 中,绑定值为 2。
oldValue:指令绑定的前一个值,仅在 update 和 componentUpdated 钩子中可用。无论值是否改变都可用。
expression:字符串形式的指令表达式。例如 v-my-directive="1 + 1" 中,表达式为 "1 + 1"。
arg:传给指令的参数,可选。例如 v-my-directive:foo 中,参数为 "foo"。
modifiers:一个包含修饰符的对象。例如:v-my-directive.foo.bar 中,修饰符对象为 { foo: true, bar: true }。
* @param {*} vnode Vue 编译生成的虚拟节点。
* @from https://cn.vuejs.org/v2/guide/custom-directive.html
*/
inserted(el, binding, vnode) {
const { value } = binding;
const authList = window.localStorage.getItem('userAuthList').split(',') || []
const hasAuth = checkAuth(value, authList);
if (!hasAuth) {
if (el.parentNode) {
el.parentNode.removeChild(el);
} else {
el.innerHTML = "";
}
} else {
el && el.setAttribute("code", value);
}
},
};
import authority from './ProxyAuth';
//注册全局自定义指令 'authority' v-authority 权限
const install = function(Vue) {
Vue.directive('authority', authority);
};
if (window.Vue) {
window.authority = authority;
Vue.use(install);
}
authority.install = install;
export default authority;
注意好import的路径是正确的
在main.js里加入
import AuthDirective from './components/AuthUtils/AuthDirective.js'
Vue.use(AuthDirective)
现在v-authority就注册好了。
哪里需要加哪里。