vue项目实现不同用户角色权限管控:
第一种方式:自定义指令实现用户角色权限控制v-permission:
实现方法:Vue.directive+install+Vue.use
步骤:1. 新建permission.js 实现自定义指令的钩子方法:
import store from '@/store'
export default {
inserted(el, binding) {
const { value } = binding
const roles = store.getters && store.getters.roles
if (value && value instanceof Array) {
if (value.length > 0) {
const permissionRoles = value
const hasPermission = roles.some(role => {
return permissionRoles.includes(role)
})
if (!hasPermission) {
el.parentNode && el.parentNode.removeChild(el)
}
}
} else {
throw new Error(`使用方式: v-permission="['admin','editor']"`)
}
}
}
- 新建index.js 将permission转为install:
import permission from './permission'
const install = function(Vue) {
Vue.directive('permission', permission)
}
if (window.Vue) {
window['permission'] = permission
Vue.use(install); // eslint-disable-line
}
permission.install = install
export default permission
- 在main.js中用use方法使用permission:
// 权限指令
import permission from './components/Permission'
Vue.use(permission)
- 在模板中使用v-permission控制访问权限:
<el-button
slot="left"
v-permission="['admin', 'storage:add']"
class="filter-item"
size="mini"
type="primary"
icon="el-icon-upload"
@click="mainadd = true"
>添加</el-button
>
第二种方式:Vue.prototype+install+v-if实现用户角色权限控制:
- 新建permission.js,将checkPer方法注册到Vue.prototype,并注册为install方法:
import store from '@/store'
/**
* @param {Array} value
* @returns {Boolean}
* @example see @/views/permission/directive.vue
*/
export default {
install(Vue) {
Vue.prototype.checkPer = (value) => {
if (value && value instanceof Array && value.length > 0) {
const roles = store.getters && store.getters.roles
const permissionRoles = value
return roles.some(role => {
return permissionRoles.includes(role)
})
} else {
console.error(`need roles! Like v-permission="['admin','editor']"`)
return false
}
}
}
}
- 在main.js中引入permission, 并用use方法:
// 权限指令
import checkPer from '@/utils/permission'
Vue.use(checkPer)
- 使用:配合 v-if 在模板中实现权限控制:
<el-table-column v-if="checkPer(['admin','app:edit','app:del'])" label="操作" width="150px" align="center">