前端实现按钮级权限控制

假装这是后端返回的按钮路由权限,包含当前登录用户每个页面的按钮权限

let buttonAuth = [
    { path: '/test', btn: ['check', 'change'] }
    // ...
]

一共有四个权限:增(add),删(delete),改(change),查(check)。path指代的当前页面路由

自定义指令实现

在 Main.ts 文件中,声明自定义指令

// 假装此用户在tset页面只有 改 和 查 的按钮权限
let buttonAuth = [
    { path: '/test', btn: ['check', 'change'] }
    // ...
]
// 自定义指令: 控制按钮级权限
app.directive('permission', {
    mounted(el, binding) {
        // console.log(el) // 元素
        // console.log(binding.value) // 值
        // console.log(binding.arg) // 路由

        // 遍历按钮数组,根绝当前的路由找到这一项的按钮权限
        let btnAuth = buttonAuth.find(item => item.path === binding.arg)
        if (btnAuth) { // 找到了
            // 不包含此按钮权限就移除按钮或者禁用按钮,这里我直接移除了
            !btnAuth.btn.includes(binding.value) && el.parentNode.removeChild(el)
        }
    }
})

test页面

<template>
    <div>
        <el-button v-permission:[currentRoute]="'add'">增加</el-button>
        <el-button v-permission:[currentRoute]="'delete'">删除</el-button>
        <el-button v-permission:[currentRoute]="'change'">修改</el-button>
        <el-button v-permission:[currentRoute]="'check'">查看</el-button>
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
// 获取当前的路由
const currentRoute = ref(router.currentRoute.value.path)
</script>

猜你喜欢

转载自blog.csdn.net/qq_52845451/article/details/134028922