vue2/vue3自定义指令——鉴权

本文介绍了如何在 Vue2 和 Vue3 中创建自定义指令,用于实现权限控制(根据用户权限动态移除按钮)和背景颜色设置。在 Vue2 中,通过在 main.ts 中全局注册自定义的 'auth' 指令,可以检查 store 中的权限并决定是否显示元素。而在 Vue3 中,将权限检查集成到应用实例的 'auth' 和 'bgColor' 指令中,分别处理权限和元素背景颜色。这些自定义指令为前端应用提供了灵活的权限管理和样式控制功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vue2:

src/directives/index.ts

import Vue from 'vue';
import store from '@/store';
export default function directive() {
    Vue.directive('auth', {
        inserted: (el, binding) => {
            if (!store.state.buttons.has(binding.value)) {
                el.remove();
            }
        }
    });
}

在main.ts中全局注册:
import directive from './directives';
Vue.use(directive);

在vue文件中使用:
<el-button  v-auth="'system:role:insert'">新增</el-button>

vue3

src/directives/index.ts

import { App } from "vue";
import { useStore } from "vuex";
import createStore from "@/store";
const list = createStore.state.buttons;
// 自定义指令,用于判断按钮权限
export default function directive(app: App) {
    app.directive("auth", {
        created: (el, binding) => {
            if (!list.has(binding.value)) {
                el.remove();
            }
        },
    });
    app.directive("bgColor", {
        beforeMount: (el, binding) => {
            el.style.backgroundColor = binding.value;
        },
    });
}
其他如上。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值