vue自定義指令和動態(tài)路由實(shí)現(xiàn)權(quán)限控制
功能概述:
- 根據(jù)后端返回接口,實(shí)現(xiàn)路由動態(tài)顯示
- 實(shí)現(xiàn)按鈕(HTML元素)級別權(quán)限控制
涉及知識點(diǎn):
- 路由守衛(wèi)
- Vuex使用
- Vue自定義指令
導(dǎo)航守衛(wèi)
前端工程采用Github開源項(xiàng)目Vue-element-admin作為模板,該項(xiàng)目地址:Github | Vue-element-admin 。
在Vue-element-admin模板項(xiàng)目的src/permission.js文件中,給出了路由守衛(wèi)、加載動態(tài)路由的實(shí)現(xiàn)方案,在實(shí)現(xiàn)了基于不同角色加載動態(tài)路由的功能。我們只需要稍作改動,就能將基于角色加載路由改造為基于權(quán)限加載路由。
導(dǎo)航守衛(wèi):可以應(yīng)用于在路由跳轉(zhuǎn)時,對用戶的登錄狀態(tài)或權(quán)限進(jìn)行判斷。項(xiàng)目中使用全局前置守衛(wèi)。參考Vue官方文檔:https://router.vuejs.org/zh/guide/advanced/navigation-guards.html
后臺返回接口

權(quán)限系統(tǒng)后臺采用基于角色的權(quán)限控制方案(role-based access control),如上圖所示,
該用戶信息接口將查詢用戶所具有的所有角色,再將這些角色的權(quán)限并集按照路由 - 操作整合在一起返回。在用戶登錄入系統(tǒng)后,我們從后臺請求獲得用戶信息(個人信息 + 權(quán)限信息),作為全局屬性儲存在前端。不同權(quán)限的用戶看到的頁面不同,依賴于這些屬性,它們決定了路由如何加載、頁面如何渲染。
這種多個組件依賴一組屬性的場景,Vue提供了VueX作為全局狀態(tài)管理方案。
使用VueX存儲權(quán)限信息
在src/store/moudules目錄下定義permission.js
1.定義異步方法,方法內(nèi)部包含HTTP請求從后臺拉取數(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ù)后臺返回的路由,生成實(shí)際可以訪問的路由
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ù)權(quán)限過濾并排序路由
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)路由 + 不需要權(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 {
// 查看是否已緩存過動態(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)路由實(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)與操作的對應(yīng)Map,url可以通過將要掛載到的vnode屬性拿到。這個方法有點(diǎn)類似于AOP,在虛擬元素掛載之后做判斷,如果沒有權(quán)限則從父元素上移除掉。
使用方法:
- 舉例一:單個按鈕 (注意雙引號套單引號的寫法)
<el-button @click.native.prevent="editUser(scope.row)" type="text" size="small" v-permission="'op_edit'"> 編輯 </el-button> - 舉例二:或判斷(傳入數(shù)組),只要擁有數(shù)組中一個權(quán)限,則保留元素,所有權(quán)限都沒有,則移除。
在上一篇博客http://www.dbjr.com.cn/article/194361.htm
下拉菜單上增加控制:
![]()

相應(yīng)數(shù)據(jù)定義中增加action屬性。
該方法無法覆蓋所有場景,所以依然給出相應(yīng)工具類:
/**
*
* @param {*當(dāng)前頁面路由} 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自定義指令和動態(tài)路由實(shí)現(xiàn)權(quán)限控制的詳細(xì)內(nèi)容,更多關(guān)于vue自定義指令和動態(tài)路由的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
iview 權(quán)限管理的實(shí)現(xiàn)
本文主要介紹了iview 權(quán)限管理,iview-admin2.0自帶權(quán)限管理。可以通過設(shè)置路由的meta對象的參數(shù)access來分配權(quán)限。感興趣的可以了解一下2021-07-07
uniapp+vue3路由跳轉(zhuǎn)傳參的實(shí)現(xiàn)
本文主要介紹了uniapp+vue3路由跳轉(zhuǎn)傳參的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-11-11
解決vue項(xiàng)目打包上服務(wù)器顯示404錯誤,本地沒出錯的問題
這篇文章主要介紹了解決vue項(xiàng)目打包上服務(wù)器顯示404錯誤,本地沒出錯的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11
安裝@vue/cli報錯npmERR gyp ERR問題及解決
這篇文章主要介紹了安裝@vue/cli報錯npmERR gyp ERR問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08

