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
),如上圖所示,
該用戶信息接口將查詢(xún)用戶所具有的所有角色,再將這些角色的權(quán)限并集按照路由 - 操作整合在一起返回。在用戶登錄入系統(tǒng)后,我們從后臺(tái)請(qǐng)求獲得用戶信息(個(gè)人信息 + 權(quán)限信息),作為全局屬性?xún)?chǔ)存在前端。不同權(quán)限的用戶看到的頁(yè)面不同,依賴(lài)于這些屬性,它們決定了路由如何加載、頁(yè)面如何渲染。
這種多個(gè)組件依賴(lài)一組屬性的場(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中的處理邏輯
// 引入store import 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支持自定義指令,用法類(lèi)似于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)類(lèi)似于AOP,在虛擬元素掛載之后做判斷,如果沒(méi)有權(quán)限則從父元素上移除掉。
使用方法:
- 舉例一:?jiǎn)蝹€(gè)按鈕 (注意雙引號(hào)套單引號(hào)的寫(xiě)法)
<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)有,則移除。
在上一篇博客http://www.dbjr.com.cn/article/194361.htm
下拉菜單上增加控制:
相應(yīng)數(shù)據(jù)定義中增加action屬性。
該方法無(wú)法覆蓋所有場(chǎng)景,所以依然給出相應(yīng)工具類(lèi):
/** * * @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)注腳本之家其它相關(guān)文章!
相關(guān)文章
websocket+Vuex實(shí)現(xiàn)一個(gè)實(shí)時(shí)聊天軟件
這篇文章主要利用websocked 建立長(zhǎng)連接,利用Vuex全局通信的特性,以及watch,computed函數(shù)監(jiān)聽(tīng)消息變化,并驅(qū)動(dòng)頁(yè)面變化實(shí)現(xiàn)實(shí)時(shí)聊天,感興趣的可以了解一下2021-08-08vue中使用js-xlsx導(dǎo)出excel的實(shí)現(xiàn)方法
本文主要介紹了vue中使用js-xlsx導(dǎo)出excel的實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-02-02vue3封裝簡(jiǎn)易的vue-echarts問(wèn)題
這篇文章主要介紹了vue3封裝簡(jiǎn)易的vue-echarts問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-05-05vue項(xiàng)目中的遇錯(cuò):Invalid?Host?header問(wèn)題
這篇文章主要介紹了vue項(xiàng)目中的遇錯(cuò):Invalid?Host?header問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-07-07Vue監(jiān)聽(tīng)數(shù)據(jù)的原理詳解
本篇文章主要介紹了Vue監(jiān)測(cè)數(shù)據(jù)的原理,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看2021-10-10vue項(xiàng)目打包之后生成一個(gè)可修改IP地址的文件(具體操作)
這篇文章主要介紹了vue項(xiàng)目打包之后生成一個(gè)可修改IP地址的文件(具體操作),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-03-03