irpas技术客

项目中添加权限校验_h&jjj_校验权限

irpas 1361

背景:在项目中,通常会给某些模块或者功能添加权限,只有有权限的人才能查看或者操作,本文记录下如何在项目中添加权限位的校验。 实现: 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中进行。


1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,会注明原创字样,如未注明都非原创,如有侵权请联系删除!;3.作者投稿可能会经我们编辑修改或补充;4.本站不提供任何储存功能只提供收集或者投稿人的网盘链接。

标签: #校验权限 #Vue