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>

效果图:


相关推荐
鹏多多2 分钟前
PC 网站接入微信登录,这 10 个坑我替你踩完了!
前端·javascript·vue.js
律宏阔34 分钟前
微信小程序使用 Orval + OpenAPI 自动生成接口:Axios 兼容踩坑记录
前端·微信小程序
律宏阔36 分钟前
微信小程序集成 TDesign 完整记录:解决 NPM packages not found
前端·微信小程序
律宏阔39 分钟前
微信小程序 ECharts 瘦身实战:分包异步化 + componentPlaceholder 避开主包 2MB 限制
前端·微信小程序
夏天要喝冰可乐1 小时前
从 Idea 到开源插件:我用 Vibe Coding 做了「文章摆渡」
前端·ai编程·vibecoding
小小小小宇1 小时前
pi agent
前端
风骏时光牛马1 小时前
AI办公能力综合性能专项测试
前端
小小小小宇1 小时前
Pi 手动添加
前端
用户298698530141 小时前
React 中 HTML 内容转 Word 文档的实现方案
javascript·react.js·html
然我1 小时前
模型不是 Agent:从零实现一个最小 Agent Loop
前端·人工智能·agent