vue-动态路由+按钮级权限(三)之按钮级权限
按钮级权限有两种方式,一种为v-if,一种为vue自定义指令,这里两种都有使用
[ "sys:user:add", "sys:user:update", "sys:user:use", "sys:system:add", "sys:system:update", "sys:system:use", "sys:system", "sys:userInfo", "sys:multiPrjs", "sys:singlePrj", "sys:singleDesign", "sys:singleDev", "sys:singleTest", "sys:singleCi" ]
上图为后台返回的数据结构
main.js里面
import { isAuth } from '@/common/permission' // 自定义指令 import PermDirective from '@/directive/Permission/index.js'; Vue.use(PermDirective); Vue.prototype.isAuth = isAuth
permission.js
import db from "@/common/storage" /** * 检查权限点工具函数 * @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; } /** * 是否有权限 * @param {*} key */ export function isAuth(key) { return ( JSON.parse(sessionStorage.getItem("permissionList") || "[]").indexOf(key) !== -1 || false ); }
directive/Permission/index.js
import perm from './Permission'; // eslint-disable-next-line func-names const install = function (Vue) { Vue.directive('perm', perm); }; if (window.Vue) { window.perm = perm; Vue.use(install); // eslint-disable-line } perm.install = install; export default perm;
directive/Permission/Permission.js
import store from "@/store"; import db from "@/common/storage" import { checkAuthority } from "@/common/permission"; export default { inserted(el, binding, vnode) { const { value } = binding; const permissions = db.ss.get('permissionList') || [] 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); } }, };
页面上使用为
v-perm="['sys:system:add']" v-if="isAuth('sys:system:use')"
最大的区别在于,1>如果是表格列,没权限需要隐藏这列表格,上面只有v-if方式可以