项目中添加权限校验

背景:在项目中,通常会给某些模块或者功能添加权限,只有有权限的人才能查看或者操作,本文记录下如何在项目中添加权限位的校验。
实现
1、在页面刷新的时候,通过接口获取当前用户所拥有的权限。
在接口正常返回之后,将返回的权限存储到Vuex(也可以自行选择存储方式)中。
代码如下:this.$store.commit('SET_AUTHS', "要存储的数据");
2、在项目中封装权限校验的方法$auth(目录可在src下面的plugin中)

import Vue from 'vue';
Vue.use({
  install: function(Vue) {
    Vue.prototype.$auth = function(powers) {
        if (!powers) return true;
        if (typeof powers === 'string') {
          powers = [powers];
        }

        powers = powers || [];

        return !!powers.find(item => this.$store.state.session.auths.indexOf(item) > -1);
    };
    // 自定义账户校验方法(例如判断一个账户是不是低级)
    Vue.prototype.$isLowerAccount = function() {
      return this.$store.state.session.mem.accountLevel=== 1;
  };
    // 跳转到登录页面
    Vue.prototype.$gotologin = function(url) {
        url = url || '/#/login';
        const isProd = process.env.NODE_ENV === 'production';
        const loginURL = (isProd ? url : null) || '/#/login';
        window.location.href = loginURL;
    };
  }
});

:可以在其中自己添加需要使用的校验方法
3、给模块或功能添加权限校验
功能添加权限判断

<v-list-item v-if="$auth('dept:update')" @click="showGroupEdit(checkedFirstGroup)">重命名</v-list-item>

例如此按钮,直接在上面加上v-if对应的权限位,即可成功实现该功能的权限添加。
模块添加权限判断
如果是在菜单上,那么可如下定义菜单:

menus: [
                {
                    title: '首页',
                    isHome: true,
                    icon: 'ifHome',
                    iconColor: '#FFF',
                    link: '/',
                    path: '',
                    auth: 'homePage'
                }
       ]

在监听到权限存储的变化之后,给权限数组赋值:

 watch: {
        '$store.state.session.auths': {
            handler() {
                this.myAuthMenus = JSON.parse(JSON.stringify(this.menus)).filter(item => {
                    if (!item.children) {
                        return this.$auth(item.auth) && (item.client ? this.$isClient(item.client) : true);
                    }
                    item.children = item.children.filter(child => {
                        if (!child.children) {
                            return this.$auth(child.auth) && (child.client ? this.$isClient(child.client) : true);
                        }
                        child.children = child.children.filter(sub => this.$auth(sub.auth) && (sub.client ? this.$isClient(sub.client) : true));
                        return child.children.length > 0;
                    });
                    return item.children.length > 0;
                });
            },
            immediate: true
        }
    },

:这里的**$isClient**是对环境的判断,如需要可在menus中菜单栏加。
至此系统的权限校验生效。对于用户以及权限的获取更新操作,应在每次页面刷新时即去获取,因此应该将操作放在App.vue中进行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值