vue-動態路由+按鈕級許可權(三)之按鈕級許可權
阿新 • • 發佈:2021-11-24
按鈕級許可權有兩種方式,一種為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方式可以