文件结构
新建directive目录,并在该目录下新增permission目录,在permission目录下新增hasPerm.js和index.js。
文件内容
hasPerm.js
//操作按钮权限控制
import store from "@/store";
export default {
/**
* 被绑定元素插入父节点时调用
* @param {*} el 指令绑定的元素
* @param {*} binding 指令信息
* @param {*} vnode 虚拟DOM节点
*/
inserted(el, binding, vnode) {
const { value } = binding;
const all_permission = "*:*:*";
const permissions = store.getters && store.getters.permissions;
if (value && value instanceof Array && value.length > 0) {
const permissionFlag = value;
const hasPermissions = permissions.some((permission) => {
return (
all_permission === permission || permissionFlag.includes(permission)
);
});
if (!hasPermissions) {
el.parentNode && el.parentNode.removeChild(el);
}
} else {
throw new Error(`请设置操作权限标签值`);
}
},
};
index.js
import hasPerm from './hasPerm'
const install = function(Vue) {
Vue.directive('hasPerm', hasPerm)
}
if (window.Vue) {
window['hasPerm'] = hasPerm
Vue.use(install);
}
export default install
全局注册
main.js
import permission from './directive/permission'
Vue.use(permission)
Vuex部分
store→getter.js
const getters = {
permissions:state=>state.user.permissions
}
export default getters
store→modules→user.js
import { getInfo } from "@/api/user";
import { getToken } from "@/utils/auth";
const getDefaultState = () => {
return {
token: getToken(),
permissions: [],
};
};
const user = {
state: getDefaultState(),
mutations: {
SET_PERMISSION: (state, permissions) => {
state.permissions = permissions;
},
},
actions: {
//获取当前登录用户信息
getInfo({ commit, state }) {
return new Promise((resolve, reject) => {
getInfo(state.token)
.then((res) => {
const { data } = res;
if (!data) {
return reject("Verification failed, please Login again.");
}
const { permissions } = data;
commit("SET_PERMISSION", permissions);
resolve(res);
})
.catch((error) => {
reject(error);
});
});
}
};
export default user;
调用
<el-button size="mini" v-hasPerm="['system:role:delete']" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
标签:const,自定义,permission,js,state,hasPerm,Vue2,按钮,permissions
From: https://www.cnblogs.com/mingcore/p/18299718