Vue3后台管理系统之权限管理-按钮权限

前言

在做后台管理系统时,需要根据用户的身份展示对应的页面、资源、按钮等。比如超级管理员在某个页面中具备新增、删除、编辑、查询、下载等按钮操作,部长具备新增、编辑、查询、下载按钮操作,而普通用户只具备查询、下载按钮操作。

思路

  1. 利用自定义指令v-directive。假设现在是sys系统设置页面中的删除按钮,order订单页面中的编辑按钮,在按钮上使用v-permission指令,判断当前用户是否具备该操作权限,渲染按钮。
  2. 使用v-if指令,判断用户是否拥有该按钮权限。与上面的做法差不多,只不过v-if不要直接使用在组件上。

创建自定义指令

首先,创建一个名为v-perm的自定义指令。这个指令会接收一个参数,即页面按钮编码,然后根据角色身份判断是否拥有此按钮的操作权限,在页面中动态渲染该按钮。

ts 复制代码
// directives/permission.js
import { DirectiveBinding } from 'vue';

export default {
  mounted(el: HTMLElement, binding: DirectiveBinding<string>) {
    const hasPermission = checkPermission(binding.value);
    if (!hasPermission) {
          el.parentNode && el.parentNode.removeChild(el); // 如果没有权限,移除该元素
    }
  },
}
export const checkPermission = ()=>{
    const userPermission = getUserPermission()
    return userPermission.includes(permission)
}
export const getUserPermission = async ()=>{
    //向后端请求获取用户的权限
    const [err,res] = await getUserInfo('admin')
    ...
}

全局注册指令

main.jsapp.js全局注册这个自定义指令。

ts 复制代码
import { createApp } from 'vue';
import permissionDirective from './directives/permission';

const app = createApp(App);
// 全局注册指令
app.directive('perm', permissionDirective);
app.mount('#app');

使用自定义指令

html 复制代码
<button v-permission="'sys_delete'" > 删除 </button>
<button v-permission="'order_edit'" > 编辑 </button>

使用v-if指令

html 复制代码
<button v-if="hasPerm('sys_delete')" > 删除 </button>
<button v-if="hasPerm('order_edit')" > 编辑 </button>
ts 复制代码
const hasPerm = async (btn_code)=>{
    const userRole = localStorage.getItem('role')
    const [err,res] = await getUserBtnPermisson(userRole)//获取该角色拥有的所有按钮操作权限
    //res = ['sys_delete','sys_edit','order_edit']
    return res.includes(btn_code)
}
相关推荐
JinSo8 小时前
我的2025年度总结:EasyEditor
前端·程序员
喝拿铁写前端12 小时前
前端开发者使用 AI 的能力层级——从表面使用到工程化能力的真正分水岭
前端·人工智能·程序员
wuhen_n12 小时前
LeetCode -- 15. 三数之和(中等)
前端·javascript·算法·leetcode
七月shi人13 小时前
AI浪潮下,前端路在何方
前端·人工智能·ai编程
非凡ghost13 小时前
MusicPlayer2(本地音乐播放器)
前端·windows·学习·软件需求
脾气有点小暴13 小时前
scroll-view分页加载
前端·javascript·uni-app
beckyye13 小时前
ant design vue Table根据数据合并单元格
前端·antd
布列瑟农的星空13 小时前
还在手动翻译国际化词条?AST解析+AI翻译实现一键替换
前端·后端·ai编程
土豆125014 小时前
Rust 错误处理完全指南:从入门到精通
前端·rust·编程语言