{ "code": 200, "data": [{ path: '/', meta: { title: '首頁', show: true, limits: ['test'], }, }, { path: '/about', meta: { title: '關於', show: false }, }, { path: '/test', meta: { title: '測試', show: true, }, }, { path: '/more', meta: { title: '更多', show: true }, children: [{ path: '/more/navone', meta: { title: '更多一', show: false }, }, { path: '/more/navtwo', meta: { title: '更多二', show: true }, } ] } ] }
import Vue from 'vue'; import store from '@/store/index' // v-permission: 功能權限指令 Vue.directive('permission', { bind(el, binding, vnode, oldVnode) { const { value } = binding const limits = store.getters && store.getters.limits if (value) { const permissionRoles = value const hasPermission = limits.some(limit => { return permissionRoles==limit }) if (!hasPermission) { el.parentNode && el.parentNode.removeChild(el) } } else { throw new Error(`need limits! Like v-permission="'test'"`) } } })
import {syncRouter, asyncRouter,router } from '@/router/index' /** * 遞歸過濾異步路由表,返回符合用戶角色權限的路由表 * @param asyncRouterMap * @param roles */ function filterAsyncRouter(asyncRouter, roles) { asyncRouter.map((item)=>{ roles.forEach((inItem)=>{ if(item.path==inItem.path){ if(item.redirect){ for(let i=0;i<inItem.children.length;i++){ if(inItem.children[i].meta.show){ item.redirect=inItem.children[i].path; break; } } } if(item.children&&inItem.children){ item.children=filterAsyncRouter(item.children,inItem.children) } item.meta=inItem.meta; } }) }) return asyncRouter; } const user = { state: { token:'', routers: syncRouter, addRouters: [], limits:[], }, mutations: { setToken(state,token){ state.token=token; }, setAuthInfo(state,theAsyncRouter){ state.addRouters = theAsyncRouter for(let i=0;i<theAsyncRouter.length;i++){ // syncRouter.push(theAsyncRouter[i]); router.options.routes.push(theAsyncRouter[i]); } router.addRoutes(theAsyncRouter); state.routers = syncRouter; console.log(state.routers) }, setLimits(state,data){ state.limits=data; } }, actions: { setToken({ commit }, token) { commit('setToken', token) }, //設置獲取的權限信息 setAuthInfo({commit},data){ console.log(data) let theAsyncRouter = filterAsyncRouter(asyncRouter,data) commit('setAuthInfo',theAsyncRouter) }, //設置功能權限 setLimits({commit},data){ commit('setLimits',data); } } }
<el-button type="primary" v-permission="'test'">測試功能顯示</el-button>
參考連接:git地址連接vue