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>

效果图:


相关推荐
lichenyang4534 小时前
Docker 学习笔记(一):为什么需要镜像、容器和仓库?
前端
kyriewen4 小时前
别再对着 TypeScript 报错发呆了:我把 10 个最常见的红色波浪线翻译成了人话
前端·javascript·typescript
IT_陈寒4 小时前
SpringBoot自动配置的坑,我的API突然就404了
前端·人工智能·后端
free355 小时前
从 0 实现一个 Tiny JavaScript VM:项目架构拆解
javascript
暴走的小呆5 小时前
Vue 2 中 Object 的变化侦测:从 getter/setter 到 Dep、Watcher、Observer
vue.js
奇奇怪怪的5 小时前
Embedding 模型 10+ 横向评测
前端
陈广亮5 小时前
Monorepo 从 0 到 1 实操指南 2026 版:pnpm catalogs + Turborepo 2.x + changesets 全链路
前端
子兮曰5 小时前
OpenMontage 深度解剖:你的 AI 编程助手,其实是个视频工作室
前端·后端·ai编程
敲代码的鱼5 小时前
PDF 预览与签名批注写回 支持安卓 iOS 鸿蒙 UTS插件
android·前端·ios