vue自定義指令和動態(tài)路由實現(xiàn)權限控制
功能概述:
根據(jù)后端返回接口,實現(xiàn)路由動態(tài)顯示 實現(xiàn)按鈕(HTML元素)級別權限控制涉及知識點:
路由守衛(wèi) Vuex使用 Vue自定義指令導航守衛(wèi)
前端工程采用Github開源項目Vue-element-admin作為模板,該項目地址:Github | Vue-element-admin 。
在Vue-element-admin模板項目的src/permission.js文件中,給出了路由守衛(wèi)、加載動態(tài)路由的實現(xiàn)方案,在實現(xiàn)了基于不同角色加載動態(tài)路由的功能。我們只需要稍作改動,就能將基于角色加載路由改造為基于權限加載路由。
導航守衛(wèi):可以應用于在路由跳轉時,對用戶的登錄狀態(tài)或權限進行判斷。項目中使用全局前置守衛(wèi)。參考Vue官方文檔:https://router.vuejs.org/zh/guide/advanced/navigation-guards.html
后臺返回接口
權限系統(tǒng)后臺采用基于角色的權限控制方案(role-based access control),如上圖所示,該用戶信息接口將查詢用戶所具有的所有角色,再將這些角色的權限并集按照路由 - 操作整合在一起返回。在用戶登錄入系統(tǒng)后,我們從后臺請求獲得用戶信息(個人信息 + 權限信息),作為全局屬性儲存在前端。不同權限的用戶看到的頁面不同,依賴于這些屬性,它們決定了路由如何加載、頁面如何渲染。
這種多個組件依賴一組屬性的場景,Vue提供了VueX作為全局狀態(tài)管理方案。
使用VueX存儲權限信息
在src/store/moudules目錄下定義permission.js
1.定義異步方法,方法內部包含HTTP請求從后臺拉取數(shù)據(jù)
import http from ’../../axios’;async function getUserInfo() { const res = await http.getUserInfo(); return res;}
使用await關鍵字,保證執(zhí)行順序正確。這里是為了保證能拿到接口返回的內容,以便于下一步處理。
const actions = { getPermissions({ commit }) { return new Promise(resolve => { getUserInfo().then(res => { if (res) { let permissionList = res.permissionList; commit(’SET_PERMISSIONS’, permissionList); // 根據(jù)后臺返回的路由,生成實際可以訪問的路由 let accessRoutes = filterAsyncRoutesByPermissions(asyncRoutes, permissionList); commit(’SET_ROUTES’, accessRoutes); commit(’SET_USER_INFO’, { name: res.name, accountName: res.accountName }) resolve(accessRoutes); } else { resolve([]); } }).catch(() => resolve([])); }) }}
VueX中action定義異步方法。
2. 定義靜態(tài)、動態(tài)路由
src/router/index.js
靜態(tài)路由:
export const constantRoutes = [ { path: ’/redirect’, component: Layout, hidden: true, children: [ { path: ’/redirect/:path(.*)’, component: () => import(’@/views/redirect/index’), }, ], , ... { path: ’/404’, component: () => import(’@/views/error-page/404’), hidden: true, }];
動態(tài)路由:
export const asyncRoutes = [ { path: ’/system’, component: Layout, name: ’系統(tǒng)管理’, meta: { title: ’系統(tǒng)管理’, icon: ’el-icon-user’, affix: true }, children: [ { path: ’/system’, component: () => import(’@/views/management/system/Index’), meta: { title: ’系統(tǒng)管理’, icon: ’el-icon-setting’, affix: true }, }, ], }...]
靜態(tài)路由中定義了所有用戶均可訪問的路由,動態(tài)路由中定義了動態(tài)加載的路由。
3.根據(jù)權限過濾并排序路由
export function filterAsyncRoutesByPermissions(routes, menus) { const res = [] routes.forEach(route => { const tmp = { ...route } let index = menus.map(menu => menu.url).indexOf(tmp.path); if (index != -1) { // 后端返回路由信息覆蓋前端定義路由信息 tmp.name = menus[index].name; // debugger; tmp.meta.title = menus[index].name; tmp.children.forEach(child => { if (child.path == tmp.path) { child.meta.title = tmp.meta.title; } }) res.push(tmp) } }); // 根據(jù)返回菜單順序,確定路由順序 /** * TODO 子菜單排序 */ res.sort((routeA, routeB) => menus.map(menu => menu.url).indexOf(routeA.path) - menus.map(menu => menu.url).indexOf(routeB.path)) return res}
根據(jù)url匹配,匹配到url的路由則加入數(shù)組。最終用戶可以訪問的路由 = 允許訪問的動態(tài)路由 + 不需要權限的靜態(tài)路由。
4.src/permission.js中的處理邏輯
// 引入storeimport store from ’./store’;const whiteList = [’/login’, ’/auth-redirect’]; // no redirect whitelist// 路由守衛(wèi)router.beforeEach(async (to, from, next) => { //start progress bar NProgress.start() if (hasToken) { if (to.path === ’/login’) { // ... 省略登出邏輯 NProgress.done(); } else { // 查看是否已緩存過動態(tài)路由 const hasRoutes = store.getters.permission_routes && store.getters.permission_routes.length > 0; if (hasRoutes) { next(); } else { try { const accessRoutes = await store.dispatch(’permission/getPermissions’); router.addRoutes(accessRoutes); const toRoute = accessRoutes.filter((route) => route.path == to.path); next({ path: toRoute.length > 0 ? toRoute[0].path : accessRoutes[0].path, replace: true }); } catch (error) { next(`/login?redirect=${to.path}`); NProgress.done(); } } } } else { if (whiteList.indexOf(to.path) !== -1) { // in the free login whitelist, go directly next(); } else { next(`/login?redirect=${to.path}`); NProgress.done(); } }});router.afterEach(() => { // finish progress bar NProgress.done();});
以上是動態(tài)路由實現(xiàn)方案。
Vue支持自定義指令,用法類似于Vue原生指令如v-model、v-on等,網上查閱到的大部分細粒度權限控制方案都使用這種方法。下面將給出我的實現(xiàn)。
自定義指令
自定義指令 v-permission:
src/directive/permission/index.js
import store from ’@/store’ export default { inserted(el, binding, vnode) { const { value } = binding const permissions = store.getters && store.getters.permissions; if (value) { // 獲取當前所掛載的vue所在的上下文節(jié)點url let url = vnode.context.$route.path; let permissionActions = permissions[url]; // console.log(permissionActions) const hasPermission = permissionActions.some(action => { if (value.constructor === Array) { // 或判斷: 只要存在任1,判定為有權限 return value.includes(action); } else { return action === value; } }) if (!hasPermission) { el.parentNode && el.parentNode.removeChild(el) } } else { throw new Error(`need further permissions!`) } }}
后端給出的權限數(shù)據(jù)是路由(url)與操作的對應Map,url可以通過將要掛載到的vnode屬性拿到。這個方法有點類似于AOP,在虛擬元素掛載之后做判斷,如果沒有權限則從父元素上移除掉。使用方法:
舉例一:單個按鈕 (注意雙引號套單引號的寫法)<el-button @click.native.prevent='editUser(scope.row)' type='text' size='small' v-permission='’op_edit’'>編輯 </el-button> 舉例二:或判斷(傳入數(shù)組),只要擁有數(shù)組中一個權限,則保留元素,所有權限都沒有,則移除。
在上一篇博客https://www.jb51.net/article/194361.htm下拉菜單上增加控制:
相應數(shù)據(jù)定義中增加action屬性。該方法無法覆蓋所有場景,所以依然給出相應工具類:
/** * * @param {*當前頁面路由} url * @param {*操作code e.g op_add } value * @return true/false 是否有該項權限 */function checkPermission(url, value) { const permissions = store.getters && store.getters.permissions; let permissionActions = permissions[url]; if (!permissionActions) { return false; } let hasPermission = permissionActions.some(action => { if (value.constructor === Array) { // 或判斷: 只要存在任1,判定為有權限 return value.includes(action); } else { return action === value; } }); return hasPermission;}
以上完成按鈕粒度權限控制。
以上就是vue自定義指令和動態(tài)路由實現(xiàn)權限控制的詳細內容,更多關于vue自定義指令和動態(tài)路由的資料請關注好吧啦網其它相關文章!
相關文章: