思路
- 先设计一个可维护的权限数据 (数据来源:1、可单独的功能点后端返回 2、可后端单独维护一个数据表 3、前端维护一个)
- 在路由前置守卫获取路由要进入的功能页 (数据有对应维护的功能页确定页面级)
- 写一个自定义指令做出判断维护的页面和做出的权限是否一致一致展示对应的按钮不一致就展示
代码
- Vue3使用pinia作为公共状态管理仓库
维护两个字段 一个是权限的数据 第二个是获取到的路由
import { defineStore } from "pinia"
import { getAuthButtonListApi } from "@/service/model/login"
interface UserStore {
authButtonList: any
routerName: string
}
export const useCounter = defineStore("user", {
state: (): UserStore => ({
authButtonList: {},
routerName: "",
}),
getters: {
authButtonListGet: (state) => state.authButtonList,
routerNameGet: (state) => state.routerName,
},
actions: {
async getAuthButtonList() {
const { data } = await getAuthButtonListApi()
this.authButtonList = data
},
async setRouterName(name: string) {
this.routerName = name
},
},
persist: {
key: "user",
storage: localStorage,
},
})
import { useCounter } from "@/store/module/user"
import type { Directive, DirectiveBinding } from "vue"
const auth: Directive = {
mounted(el: HTMLElement, binding: DirectiveBinding) {
const { value } = binding
const authStore = useCounter()
const currentPageRoles = authStore.authButtonListGet[authStore.routerName] ?? []
if (value instanceof Array && value.length) {
const hasPermission = value.every((item) => currentPageRoles.includes(item))
if (!hasPermission) el.remove()
} else {
if (!currentPageRoles.includes(value)) el.remove()
}
},
}
export default auth
{
key: "operations",
title: "Operations",
cellRenderer: () => (
<>
<ElButton size="small" v-auth="edit">
Edit
</ElButton>
<ElButton size="small" type="danger" v-auth="delete">
Delete
</ElButton>
</>
),
width: 150,
align: "center",
}