// 注意这个数组保存着当前用户的所有权限code // 但是这个数据是在用户登录之后才初始化的 // 也就是说没有登录的用户是没有任何权限的 let login = false; let currentUserPermissionCode: string[] = []; // 在用户登录时需要初始化该用户的权限列表 export function loginAuth(codeList: string[]) { login = true; currentUserPermissionCode = codeList || []; } // 在用户登出时需要重置数据 export function logoutAuth() { login = false; currentUserPermissionCode = []; } // 判断当前用户是否已经登录 export function isLogin() { return login; } // 在正常ts代码中使用hasAuth方法 export function hasAuth(code: string | string[]) { const codeArr = typeof code === 'string' ? [code] : code; return codeArr.every(c => currentUserPermissionCode.indexOf(c) >= 0); } // 在模版中使用指令v-auth export function createAuthPlugin() { return { install(app: any) { app.directive('auth', function (el: any, binding: any) { const permission = binding.value; if (!hasAuth(permission)) { if (binding?.modifiers?.disable) { // v-auth.disable="permission" // 可以给按钮置灰,而不是隐藏 el.disabled = true; } else { el && el.parentNode && el.parentNode.removeChild(el); } } }); }, }; } // 在下方定义使用到的所有权限码 // 禁止直接在代码中使用字符串作为权限码 export const USER_ADD = 'user:add'; export const USER_LOOK = 'user:look';