vue自定义权限标签
技术栈
- vuex
- vue自定义标签
开门见山
- 创建directive
-
hasPermi.js
/** * v-hasPermi 操作权限处理 */ import store from '@/store' export default { inserted(el, binding, vnode) { const { value } = binding const all_permission = "*:*:*"; const permissions = store.getters && store.getters.permissions if (value && value instanceof Array && value.length > 0) { const permissionFlag = value const hasPermissions = permissions.some(permission => { return all_permission === permission || permissionFlag.includes(permission) }) if (!hasPermissions) { el.parentNode && el.parentNode.removeChild(el) } } else { throw new Error(`请设置操作权限标签值`) } } }
-
index.js
import hasPermi from './permission/hasPermi' const install = function(Vue) { Vue.directive('hasPermi', hasPermi) } if (window.Vue) { window['hasPermi'] = hasPermi Vue.use(install); // eslint-disable-line } export default install
- store
-
user.js
import {getPermissions} from "@/api/token/assets"; import async from "async"; const user = { state: { permissions: [] }, mutations: { SET_PERMISSIONS: (state, permissions) => { state.permissions = permissions } }, actions: { // 获取用户信息 GetInfo({***mit}, query) { return new Promise((resolve, reject) => { // 获取权限信息(请求后台数据接口) getPermissions(query).then(res => { if ( res.code == 200 ) { ***mit('SET_PERMISSIONS', res.data) } resolve(res) }).catch(error => { reject(error) }) }) } } } export default user
-
getters.js
const getters = { token: state => state.user.token, permissions: state => state.user.permissions } export default getters
-
index.js
import Vue from 'vue' import Vuex from 'vuex' import user from './modules/user' import getters from './getters' Vue.use(Vuex) const store = new Vuex.Store({ modules: { user }, getters }) export default store
-
src目录下创建permission.js
import router from './router' import store from './store' import { Message } from 'element-ui' router.beforeEach((to, from, next) => { // to.query 获取url路由请求参数,传递给后端使用 store.dispatch('GetInfo',to.query).then(() => { next() }).catch(err => { Message.error(err) }) })
-
src下的main.js使用
import Vue from 'vue' import App from './App.vue' import router from './router' import ElementUI from 'element-ui'; import 'element-ui/lib/theme-chalk/index.css'; import directive from './directive' // directive import store from './store' import './permission' // permission control Vue.use(ElementUI) Vue.use(directive) new Vue({ router, store, render: h => h(App) }).$mount('#app')
-
按钮标签
<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['btn:delete']" >删除 </el-button>
说明:
如果后台接口返回的按钮权限数据里包含btn:delete则删除按钮显示,否则不显示
后台返回数据如下:
[ "btn:list", "btn:add", "btn:delete", "btn:edit" ]