vue自定義指令和動(dòng)態(tài)路由實(shí)現(xiàn)權(quán)限控制
功能概述:
根據(jù)后端返回接口,實(shí)現(xiàn)路由動(dòng)態(tài)顯示 實(shí)現(xiàn)按鈕(HTML元素)級(jí)別權(quán)限控制涉及知識(shí)點(diǎn):
路由守衛(wèi) Vuex使用 Vue自定義指令導(dǎo)航守衛(wèi)
前端工程采用Github開(kāi)源項(xiàng)目Vue-element-admin作為模板,該項(xiàng)目地址:Github | Vue-element-admin 。
在Vue-element-admin模板項(xiàng)目的src/permission.js文件中,給出了路由守衛(wèi)、加載動(dòng)態(tài)路由的實(shí)現(xiàn)方案,在實(shí)現(xiàn)了基于不同角色加載動(dòng)態(tài)路由的功能。我們只需要稍作改動(dòng),就能將基于角色加載路由改造為基于權(quán)限加載路由。
導(dǎo)航守衛(wèi):可以應(yīng)用于在路由跳轉(zhuǎn)時(shí),對(duì)用戶的登錄狀態(tài)或權(quán)限進(jìn)行判斷。項(xiàng)目中使用全局前置守衛(wèi)。參考Vue官方文檔:https://router.vuejs.org/zh/guide/advanced/navigation-guards.html
后臺(tái)返回接口
權(quán)限系統(tǒng)后臺(tái)采用基于角色的權(quán)限控制方案(role-based access control),如上圖所示,該用戶信息接口將查詢用戶所具有的所有角色,再將這些角色的權(quán)限并集按照路由 - 操作整合在一起返回。在用戶登錄入系統(tǒng)后,我們從后臺(tái)請(qǐng)求獲得用戶信息(個(gè)人信息 + 權(quán)限信息),作為全局屬性儲(chǔ)存在前端。不同權(quán)限的用戶看到的頁(yè)面不同,依賴于這些屬性,它們決定了路由如何加載、頁(yè)面如何渲染。
這種多個(gè)組件依賴一組屬性的場(chǎng)景,Vue提供了VueX作為全局狀態(tài)管理方案。
使用VueX存儲(chǔ)權(quán)限信息
在src/store/moudules目錄下定義permission.js
1.定義異步方法,方法內(nèi)部包含HTTP請(qǐng)求從后臺(tái)拉取數(shù)據(jù)
import http from ’../../axios’;async function getUserInfo() { const res = await http.getUserInfo(); return res;}
使用await關(guān)鍵字,保證執(zhí)行順序正確。這里是為了保證能拿到接口返回的內(nèi)容,以便于下一步處理。
const actions = { getPermissions({ commit }) { return new Promise(resolve => { getUserInfo().then(res => { if (res) { let permissionList = res.permissionList; commit(’SET_PERMISSIONS’, permissionList); // 根據(jù)后臺(tái)返回的路由,生成實(shí)際可以訪問(wèn)的路由 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)、動(dòng)態(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, }];
動(dòng)態(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)路由中定義了所有用戶均可訪問(wèn)的路由,動(dòng)態(tài)路由中定義了動(dòng)態(tài)加載的路由。
3.根據(jù)權(quán)限過(guò)濾并排序路由
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ù)組。最終用戶可以訪問(wèn)的路由 = 允許訪問(wèn)的動(dòng)態(tài)路由 + 不需要權(quán)限的靜態(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 { // 查看是否已緩存過(guò)動(dòng)態(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();});
以上是動(dòng)態(tài)路由實(shí)現(xiàn)方案。
Vue支持自定義指令,用法類似于Vue原生指令如v-model、v-on等,網(wǎng)上查閱到的大部分細(xì)粒度權(quán)限控制方案都使用這種方法。下面將給出我的實(shí)現(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) { // 獲取當(dāng)前所掛載的vue所在的上下文節(jié)點(diǎn)url let url = vnode.context.$route.path; let permissionActions = permissions[url]; // console.log(permissionActions) const hasPermission = permissionActions.some(action => { if (value.constructor === Array) { // 或判斷: 只要存在任1,判定為有權(quán)限 return value.includes(action); } else { return action === value; } }) if (!hasPermission) { el.parentNode && el.parentNode.removeChild(el) } } else { throw new Error(`need further permissions!`) } }}
后端給出的權(quán)限數(shù)據(jù)是路由(url)與操作的對(duì)應(yīng)Map,url可以通過(guò)將要掛載到的vnode屬性拿到。這個(gè)方法有點(diǎn)類似于AOP,在虛擬元素掛載之后做判斷,如果沒(méi)有權(quán)限則從父元素上移除掉。使用方法:
舉例一:?jiǎn)蝹€(gè)按鈕 (注意雙引號(hào)套單引號(hào)的寫法)<el-button @click.native.prevent='editUser(scope.row)' type='text' size='small' v-permission='’op_edit’'>編輯 </el-button> 舉例二:或判斷(傳入數(shù)組),只要擁有數(shù)組中一個(gè)權(quán)限,則保留元素,所有權(quán)限都沒(méi)有,則移除。
在上一篇博客https://www.jb51.net/article/194361.htm下拉菜單上增加控制:
相應(yīng)數(shù)據(jù)定義中增加action屬性。該方法無(wú)法覆蓋所有場(chǎng)景,所以依然給出相應(yīng)工具類:
/** * * @param {*當(dāng)前頁(yè)面路由} url * @param {*操作code e.g op_add } value * @return true/false 是否有該項(xiàng)權(quán)限 */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,判定為有權(quán)限 return value.includes(action); } else { return action === value; } }); return hasPermission;}
以上完成按鈕粒度權(quán)限控制。
以上就是vue自定義指令和動(dòng)態(tài)路由實(shí)現(xiàn)權(quán)限控制的詳細(xì)內(nèi)容,更多關(guān)于vue自定義指令和動(dòng)態(tài)路由的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. ASP基礎(chǔ)知識(shí)VBScript基本元素講解2. Python requests庫(kù)參數(shù)提交的注意事項(xiàng)總結(jié)3. IntelliJ IDEA導(dǎo)入jar包的方法4. ajax請(qǐng)求添加自定義header參數(shù)代碼5. 使用Python和百度語(yǔ)音識(shí)別生成視頻字幕的實(shí)現(xiàn)6. 詳談ajax返回?cái)?shù)據(jù)成功 卻進(jìn)入error的方法7. Kotlin + Flow 實(shí)現(xiàn)Android 應(yīng)用初始化任務(wù)啟動(dòng)庫(kù)8. 使用python 計(jì)算百分位數(shù)實(shí)現(xiàn)數(shù)據(jù)分箱代碼9. vue-electron中修改表格內(nèi)容并修改樣式10. python操作mysql、excel、pdf的示例
