vue自定义权限标签
技术栈
- vuex
- vue自定义标签
开门见山
- 创建directive
- hasPermi.js
/** * v-hasPermi 操作权限处理 */import store from'@/store'exportdefault{inserted(el, binding, vnode){const{ value }= binding const all_permission ="*:*:*";const permissions = store.getters && store.getters.permissions if(value && value instanceofArray&& 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{thrownewError(`请设置操作权限标签值`)}}}
- index.js
import hasPermi from'./permission/hasPermi'constinstall=function(Vue){ Vue.directive('hasPermi', hasPermi)}if(window.Vue){ window['hasPermi']= hasPermi Vue.use(install);// eslint-disable-line}exportdefault install
- store
- user.js
import{getPermissions}from"@/api/token/assets";importasyncfrom"async";const user ={state:{permissions:[]},mutations:{SET_PERMISSIONS:(state, permissions)=>{ state.permissions = permissions }},actions:{// 获取用户信息GetInfo({commit}, query){returnnewPromise((resolve, reject)=>{// 获取权限信息(请求后台数据接口)getPermissions(query).then(res=>{if( res.code ==200){commit('SET_PERMISSIONS', res.data)}resolve(res)}).catch(error=>{reject(error)})})}}}exportdefault 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'// directiveimport store from'./store'import'./permission'// permission controlVue.use(ElementUI)Vue.use(directive)newVue({ router, store,render:h=>h(App)}).$mount('#app')
- 按钮标签
<el-buttonsize="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"]
本文转载自: https://blog.csdn.net/succeedcow/article/details/127170397
版权归原作者 ByCode 所有, 如有侵权,请联系我们删除。
版权归原作者 ByCode 所有, 如有侵权,请联系我们删除。