如何在Vue中实现前端权限控制

1. 在utils中创建自定义指令文件(permissionDirect.js)

export const hasPermission = {
    install(Vue) {
        Vue.directive('hasPermission', {
            bind(el, binding, node) {
                var flag = false;//默认不显示
                let userInfo = node.context.$store.state.userInfoVO;
                //获取使用组件的value中
                var value = binding.value;
                //若是超级管理员
                let len = userInfo.permissions.length;
                for (let index = 0; index < len; index++) {
                    if (userInfo.permissions[index].permissionName === 'super_admin') {
                        flag = true;
                        break;
                    }
                }

                for (let index = 0; index < userInfo.permissions.length; index++) {
                    if (userInfo.permissions[index].permissionName == value) {
                        //若有该权限的按钮则显示
                        flag = true;
                    }

                }
                if (!flag) {
                    el.setAttribute("disabled", true);
                    el.classList.add("is-disabled");
                }
            }
        })
    }
}

2. 在main.js中进行引入

import {hasPermission} from './utils/permissionDirect'

const Plugins = [hasPermission]
Plugins.map((plugin)=>{
  Vue.use(plugin)
})

3. 完成上述步骤就可以在任意组件中进行使用

<!-- 通过判断该用户对应的角色是否有对应的权限来控制button是否可用 -->
<template slot-scope="scope">
              <el-button
                v-hasPermission="'log:login:delete'"
                type="text"
                size="mini"
                icon="el-icon-delete"
                @click="del(scope.row.loginRecordId)"
              >删除</el-button>
            </template>

扫码关注下方公众号,点击关注,获取详情信息,任何相关问题直接留言即可。

Alt

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值