Mixin全局配置:src/mixin/action.js
/*
* <el-button v-if="checkAction('role_add')">{{role_add:新增权限}}</el-button>
* - 当前用户没有权限时,组件上使用了该指令则会被隐藏 v-if
*/
const actionMixin = {
methods: {
checkAction(value) {
// 获得当前路由权限配置
console.log('checkAction $route',this.$route)
console.log('checkAction action',this.$route.meta.actions)
const actions = this.$route.meta.actions || []
// 判定权限组是否有改权限
return actions.includes(value)
}
}
}
export default actionMixin
全局指令:src/directive/index.js action.js
// action.js
/**
* <el-button v-action:role_add>{{role_add:新增权限}}</el-button>
* - 当前用户没有权限时,组件上使用了该指令则会被隐藏 v-if
*/
export default {
inserted: function(el, binding, vNode) {
console.log('binding.arg',binding.arg)
console.log(' vNode.context.$route', vNode.context.$route)
console.log(' vNode.context.$route.action', vNode.context.$route.actions)
const actionName = binding.arg
const actions = vNode.context.$route.meta.actions
if (!actions || !actions.includes(actionName)) {
el.parentNode && el.parentNode.removeChild(el) || (el.style.display = 'none')
}
}
}
// index.js
import Action from './aciton'
import Vue from 'vue'
const install = function(Vue) {
Vue.directive('action', Action)
}
if (window.Vue) {
window['action'] = Action
Vue.use(install)
}
Action.install = install
export default Action
main.js 文件修改
// 全局指令
import Action from './directive/aciton/index' // 权限判断指令
Vue.use(Action)
// 全局Mixin
import actionMixins from './mixin/aciton' // 权限判断方法
Vue.mixin(actionMixins)
在路由页配置新页面后刷新获得路由,点击菜单进入首页配置
// c-index.vue
<template>
<div>
<div>测试首页配置页面</div>
<div>admin账号具备权限{{$route.meta.actions}}</div>
<!-- 权限测试页面 -->
<el-button v-action:role_add>新增</el-button>
<el-button v-action:role_audit>审核</el-button>
<el-button v-action:role_view>查看</el-button>
<el-button v-if="checkAction('role_delete')">删除</el-button>
<el-button v-if="checkAction('role_update')">编辑</el-button>
</div>
</template>
页面显示