一、src文件夹下新建utils文件夹,文件夹下新建authoruty.js文件:
/**
* 检查权限点工具函数
* @param {*} permissionCode 元素权限点
* @param {*} permissions 所有权限点
*/
export function checkAuthority(permissionCode, permissions) {
let hasPermission = true;
if (permissionCode) {
if (permissionCode instanceof Array && permissionCode.length > 0) {
hasPermission = permissions.some(it =>
permissionCode.includes(it)
);
console.log('permissionCode---', permissionCode)
console.log('hasPermission---1', hasPermission)
} else {
hasPermission = permissions.some(item => item === permissionCode);
console.log('hasPermission---2', hasPermission)
}
}
return hasPermission;
}
二、src文件下新建directive文件夹,随之再建立Authority文件夹,并在其下新建Authority.js文件和index.js文件,
- Authority.js文件代码:
import store from "@/store";
import { checkAuthority } from "@/utils/authority";
// console.log('store-----', store.state.user.permission)
console.log("store-----", store);
export default {
inserted(el, binding, vnode) {
const { value } = binding;
const permissions = JSON.parse(localStorage.getItem('permissionData')) || []
console.log('permissionList---', permissions)
const hasPermission = checkAuthority(value, permissions);
if (!hasPermission) {
// eslint-disable-next-line no-unused-expressions
if (el.parentNode) {
el.parentNode.removeChild(el);
} else {
el.innerHTML = "";
}
} else {
el && el.setAttribute("code", value);
}
},
};
- index.js文件代码:
import authority from './Authority';
// eslint-disable-next-line func-names
const install = function(Vue) {
Vue.directive('authority', authority);
};
if (window.Vue) {
window.authority = authority;
Vue.use(install); // eslint-disable-line
}
authority.install = install;
export default authority;
(备注: 权限点集合permissionData在登录时已经存到localStorage里面了,取值,直接JSON.parse(localStorage.getItem('permissionData')))
三、main.js文件里引入:
import AuthorityDirective from '@/directive/Authority/index.js'; // 自定义指令
Vue.use(AuthorityDirective);
四、使用:
<el-button type="primary" v-authority="['Table_Write']">show</el-button>
补充:
权限点集合是一个纯数组集合,该数据模拟从后台获取到的数据:
permissionData = ['Table_Write', 'Table_Read', 'Form_Write', 'Form_Read']
获取到后,在登录时立即存入localStorage。