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>

效果图:


相关推荐
小吕学编程8 分钟前
ES练习册
java·前端·elasticsearch
Asthenia041215 分钟前
Netty编解码器详解与实战
前端
袁煦丞20 分钟前
每天省2小时!这个网盘神器让我告别云存储混乱(附内网穿透神操作)
前端·程序员·远程工作
Mr.app1 小时前
vue mixin混入与hook
vue.js
一个专注写代码的程序媛1 小时前
vue组件间通信
前端·javascript·vue.js
一笑code1 小时前
美团社招一面
前端·javascript·vue.js
懒懒是个程序员2 小时前
layui时间范围
前端·javascript·layui
NoneCoder2 小时前
HTML响应式网页设计与跨平台适配
前端·html
凯哥19702 小时前
在 Uni-app 做的后台中使用 Howler.js 实现强大的音频播放功能
前端
心宽体胖连壮实2 小时前
记录一次 MarchingSquaresJS 使用经历
vue.js