vue3用自定义指令实现按钮权限

1,编写permission.ts文件

在src/utils/permission.ts

复制代码
import type { Directive } from "vue";
export const permission:Directive={
    // 在绑定元素的父组件被挂载后调用
    mounted(el,binding){
        // el:指令所绑定的元素,可以用来直接操作 DOM
        // binding:我们通过自定义指令传递的各种参数
        const {value}=binding;
        
        // 这里模拟后端返回来的数据,一般是登录过后存在缓存或者pinia里
        const permissionButton = ['add', 'edit']
        
        if (value && value instanceof Array && value.length > 0) {
            // 有权限
             const hasPermission = permissionButton.some((role: string) => {
                console.log('role',role);
                return value.includes(role);
            }); 
            // 没有权限
            if (!hasPermission) {
                el.style.display = 'none';
            }
        }
    }
}

2,在main.ts注册

复制代码
import { createApp, type Directive } from 'vue'
import pinia from './stores'
import App from './App.vue'
import router from './router'

// 导入自定义指令
import * as directives from '@/utils/permission'

const app = createApp(App)
app.use(pinia)
app.use(router)
app.mount('#app')

//挂载自定义指令
Object.keys(directives).forEach(key => {
    app.directive(key, (directives as { [key: string]: Directive })[key]);
  });

3,在任意vue文件里使用

复制代码
<template>
  <div >
    <button v-permission="['add']">增加</button >
    <button v-permission="['delete']">删除</button >
    <button v-permission="['edit']">修改</button >
    <button v-permission="['query']">查看</button >
    <button v-permission="['export']">导出</button >
  </div>
</template>

效果图:


相关推荐
NiceCloud喜云8 小时前
Opus 4.8 的 Effort Control 怎么选:Low 到 Max 五档策略
android·java·大数据·前端·c++·python·spring
wordbaby8 小时前
React Native + RNOH:跨页面数据回传的最佳实践与避坑指南
前端·react native
GISer_Jing8 小时前
Three.js着色器编译机制深度解析
javascript·webgl·着色器
丷丩9 小时前
MapLibre GL JS第22课:查看本地GeoJSON
前端·javascript·map·mapbox·maplibre gl js
油炸自行车9 小时前
Claude Code 错误:API Error: 400 Failed to deserialize the JSON body into the
开发语言·javascript·json·trae·claude code·api error 400
Front思10 小时前
AI前端工程师需要具备能力+
前端·人工智能·ai
ZC跨境爬虫11 小时前
跟着 MDN 学CSS day_29:(掌握文本与字体样式的核心艺术)
前端·css·ui·html·tensorflow
李子琪。12 小时前
网络空间安全深度实战:CSRF 漏洞原理剖析与基于 Token 的纵深防御体系构建(全栈实验报告)
前端·安全·csrf
冰暮流星12 小时前
javascript之history对象介绍
前端·笔记
IT_陈寒13 小时前
Vite热更新失灵?你可能漏了这个配置
前端·人工智能·后端