1.按钮根据后端返回数据决定展示与否
根据right中的数据对应增删改查按钮
const menuList = [
{'id': 1, path:'/uploadSpec','authName': "上传spec", icon: 'User', children:[], rights:['view','add','edit','delete']},
{'id': 2, path:'/showSpec', 'authName': "Spec预览", icon: 'DataAnalysis',children:[], rights:['view','add','edit','delete']},
{'id': 3, path:'/generateTxt', 'authName': "生成测试数据", icon: 'DataAnalysis',children:[], rights:['view','add','edit','delete']},
{'id': 4, path:'/generateCronjob', 'authName': "生成转码程序", icon: 'Promotion',children:[], rights:['view','add','edit','delete']},
{'id': 5, path:'/pdfCompare', 'authName': "PDF文档对比", icon: 'DocumentCopy',children:[], rights:['view','add','edit','delete']},
{'id': 6, path:'/resourceUpdate', 'authName': "资源更新管理", icon: 'Management',children:[], rights:['view','add','edit','delete']},
{'id': 7, path:'/generateTestCase', 'authName': "自动生成ST/SIT案例", icon: 'Files',children:[], rights:['view','add','edit','delete']},
{'id': 8, path:'/userManagement', 'authName': "用户管理", icon: 'User', rights:['view']},
{'id': 9, path:'/roleManagement', 'authName': "角色管理", icon: 'Stamp', rights:['view']},
]
2.在设置动态路由时,将rights权限数据设置到路由元数据中meta
initDynamicRoutes给用户对应的router中动态添加meta元数据后,permission.js中通过router.currentRoute就可以获取
export const initDynamicRoutes = async () => {
const menuList = Store.state.user.menuList;;
const rights = Store.state.user.rights;;
menuList.length > 0 && menuList.forEach(item => {
if (item.path) {
const temp = routeMapping[item.path];
// 动态添加rights到meta中,使用自定义指令时通过rights鉴别其是否有该权限
temp.meta.rights = item.rights;
router.addRoute("Home", temp);
}
});
router.addRoute({ name: 'NotFound', path: '/404', title: "页面不存在", component: NotFound });
router.addRoute({ path: '/:pathMatch(.*)', redirect: '/404' });
}
3.按钮上通过自定义指令控制
directives/permission.js文章来源:https://www.toymoban.com/news/detail-677397.html
获取路由元数据中的rights权限和按钮上的action记录权限做比较:如果包含则有该权限,否则无权限,进行删除元素或者设置disabled文章来源地址https://www.toymoban.com/news/detail-677397.html
import router from "@/route/route"
import { nextTick } from 'vue'
export const vHas = {
created(el, binding, vnode, prevVnode) {
let metaRights = router.currentRoute.value.meta.rights;
let action = binding.value.action;
let effect = binding.value.effect;
if (!metaRights.includes(action)) {
// 注意要使用nextTick,才能立即修改DOM
nextTick(() => {
if (effect === "disabled") {
el.ariaDisabled = 'true';
el.classList.add('is-disabled')
} else {
if (el.parentNode)
el.parentNode.removeChild(el)
else
el.remove();
}
});
}
}
}
4.页面中使用v-has指令
<template>
<div>
<el-button type="primary" v-has="{action:'add',effect:'disabled'}">增加角色</el-button>
<el-button type="success" v-has="{action:'edit'}">修改角色</el-button>
<el-button type="info" v-has="{action:'view'}">查看角色</el-button>
<el-button type="warning" v-has="{action:'delete',effect:'disabled'}">删除角色</el-button>
</div>
</template>
<script setup>
import { vHas } from "@/directives/permission"
</script>
到了这里,关于vue权限管理——按钮控制的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!