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>

效果图:


相关推荐
qq_4221525723 分钟前
图片格式转换工具怎么选?JPEG、PNG、WebP、AVIF 格式对比与在线转换方案实测
前端
xiaofeichaichai31 分钟前
ES 新特性九年速览:从 ES2016 到 ES2024
前端·javascript·es6
2401_8346369932 分钟前
Keepalived + LVS (DR) + Nginx + NFS 高可用 Web 集群部署实战手册
前端·nginx·lvs
和你看星星35 分钟前
我把代码排查流程做成了一个 Codex Skill
前端
excel40 分钟前
AI 冲击下的前端发展指引:从工具到价值的重塑
前端
文心快码BaiduComate40 分钟前
提升组织级AI Coding质量:电商搜索项目实践
前端·后端·程序员
excel1 小时前
AI 时代前端转型:模型训练才是未来的核心竞争力
前端
放下华子我只抽RuiKe51 小时前
FastAPI 全栈后端(四):认证与授权
开发语言·前端·javascript·python·深度学习·react.js·fastapi
持敬chijing1 小时前
Web渗透之前后端漏洞-文件包含漏洞
前端·安全·web安全·网络安全·网络攻击模型·安全威胁分析
CV艺术家2 小时前
前端免费高效的接入天气组件(天气网),控制组件的样式
前端