vue權(quán)限路由實(shí)現(xiàn)的方法示例總結(jié)
使用全局路由守衛(wèi)
實(shí)現(xiàn)
前端定義好路由,并且在路由上標(biāo)記相應(yīng)的權(quán)限信息
const routerMap = [
{
path: '/permission',
component: Layout,
redirect: '/permission/index',
alwaysShow: true, // will always show the root menu
meta: {
title: 'permission',
icon: 'lock',
roles: ['admin', 'editor'] // you can set roles in root nav
},
children: [{
path: 'page',
component: () => import('@/views/permission/page'),
name: 'pagePermission',
meta: {
title: 'pagePermission',
roles: ['admin'] // or you can only set roles in sub nav
}
}, {
path: 'directive',
component: () => import('@/views/permission/directive'),
name: 'directivePermission',
meta: {
title: 'directivePermission'
// if do not set roles, means: this page does not require permission
}
}]
}]
全局路由守衛(wèi)每次都判斷用戶是否已經(jīng)登錄,沒有登錄則跳到登錄頁。已經(jīng)登錄(已經(jīng)取得后臺返回的用戶的權(quán)限信息(角色之類的)),則判斷當(dāng)前要跳轉(zhuǎn)的路由,用戶是否有權(quán)限訪問(根據(jù)路由名稱到全部路由里找到對應(yīng)的路由,判斷用戶是否具備路由上標(biāo)注的權(quán)限信息(比如上面的roles: ['admin', 'editor']))。沒有權(quán)限則跳到事先定義好的界面(403,404之類的)。
這種方式,菜單可以直接用路由生成(用戶沒有權(quán)限的菜單也會顯示,點(diǎn)擊跳轉(zhuǎn)的時(shí)候才做權(quán)限判斷),也可以在用戶登錄后根據(jù)用戶權(quán)限把路由過濾一遍生成菜單(菜單需要保存在vuex里)。
目前iview-admin還是用的這種方式
缺點(diǎn)
- 加載所有的路由,如果路由很多,而用戶并不是所有的路由都有權(quán)限訪問,對性能會有影響。
- 全局路由守衛(wèi)里,每次路由跳轉(zhuǎn)都要做權(quán)限判斷。
- 菜單信息寫死在前端,要改個(gè)顯示文字或權(quán)限信息,需要重新編譯
- 菜單跟路由耦合在一起,定義路由的時(shí)候還有添加菜單顯示標(biāo)題,圖標(biāo)之類的信息,而且路由不一定作為菜單顯示,還要多加字段進(jìn)行標(biāo)識
登錄頁與主應(yīng)用分離
針對前一種實(shí)現(xiàn)方式的缺點(diǎn),可以將登錄頁與主應(yīng)用放到不同的頁面(不在同一個(gè)vue應(yīng)用實(shí)例里)。
實(shí)現(xiàn)
登錄成功后,進(jìn)行頁面跳轉(zhuǎn)(真正的頁面跳轉(zhuǎn),不是路由跳轉(zhuǎn)),并將用戶權(quán)限傳遞到主應(yīng)用所在頁面,主應(yīng)用初始化之前,根據(jù)用戶權(quán)限篩選路由,篩選后的路由作為vue的實(shí)例化參數(shù),而不是像前一種方式所有的路由都傳遞進(jìn)去,也不需要在全局路由守衛(wèi)里做權(quán)限判斷了。
缺點(diǎn)
- 需要做頁面跳轉(zhuǎn),不是純粹的單頁應(yīng)用
- 菜單信息寫死在前端,要改個(gè)顯示文字或權(quán)限信息,需要重新編譯
- 菜單跟路由耦合在一起,定義路由的時(shí)候還有添加菜單顯示標(biāo)題,圖標(biāo)之類的信息,而且路由不一定作為菜單顯示,還要多加字段進(jìn)行標(biāo)識
使用addRoutes動(dòng)態(tài)掛載路由
addRoutes允許在應(yīng)用初始化之后,動(dòng)態(tài)的掛載路由。有了這個(gè)新姿勢,就不用像前一種方式那樣要在應(yīng)用初始化之要對路由進(jìn)行篩選。
實(shí)現(xiàn)
應(yīng)用初始化的時(shí)候先掛載不需要權(quán)限控制的路由,比如登錄頁,404等錯(cuò)誤頁。
有個(gè)問題,addRoutes應(yīng)該何時(shí)調(diào)用,在哪里調(diào)用
登錄后,獲取用戶的權(quán)限信息,然后篩選有權(quán)限訪問的路由,再調(diào)用addRoutes添加路由。這個(gè)方法是可行的。但是不可能每次進(jìn)入應(yīng)用都需要登錄,用戶刷新瀏覽器又要登陸一次。
所以addRoutes還是要在全局路由守衛(wèi)里進(jìn)行調(diào)用
import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'// progress bar style
import { getToken } from '@/utils/auth' // getToken from cookie
NProgress.configure({ showSpinner: false })// NProgress Configuration
// permission judge function
function hasPermission(roles, permissionRoles) {
if (roles.indexOf('admin') >= 0) return true // admin permission passed directly
if (!permissionRoles) return true
return roles.some(role => permissionRoles.indexOf(role) >= 0)
}
const whiteList = ['/login', '/authredirect']// no redirect whitelist
router.beforeEach((to, from, next) => {
NProgress.start() // start progress bar
if (getToken()) { // determine if there has token
/* has token*/
if (to.path === '/login') {
next({ path: '/' })
NProgress.done() // if current page is dashboard will not trigger afterEach hook, so manually handle it
} else {
if (store.getters.roles.length === 0) { // 判斷當(dāng)前用戶是否已拉取完user_info信息
store.dispatch('GetUserInfo').then(res => { // 拉取user_info
const roles = res.data.roles // note: roles must be a array! such as: ['editor','develop']
store.dispatch('GenerateRoutes', { roles }).then(() => { // 根據(jù)roles權(quán)限生成可訪問的路由表
router.addRoutes(store.getters.addRouters) // 動(dòng)態(tài)添加可訪問路由表
next({ ...to, replace: true }) // hack方法 確保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
})
}).catch((err) => {
store.dispatch('FedLogOut').then(() => {
Message.error(err || 'Verification failed, please login again')
next({ path: '/' })
})
})
} else {
// 沒有動(dòng)態(tài)改變權(quán)限的需求可直接next() 刪除下方權(quán)限判斷 ↓
if (hasPermission(store.getters.roles, to.meta.roles)) {
next()//
} else {
next({ path: '/401', replace: true, query: { noGoBack: true }})
}
// 可刪 ↑
}
}
} else {
/* has no token*/
if (whiteList.indexOf(to.path) !== -1) { // 在免登錄白名單,直接進(jìn)入
next()
} else {
next('/login') // 否則全部重定向到登錄頁
NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
}
}
})
router.afterEach(() => {
NProgress.done() // finish progress bar
})
關(guān)鍵的代碼如下
if (store.getters.roles.length === 0) { // 判斷當(dāng)前用戶是否已拉取完user_info信息
store.dispatch('GetUserInfo').then(res => { // 拉取user_info
const roles = res.data.roles // note: roles must be a array! such as: ['editor','develop']
store.dispatch('GenerateRoutes', { roles }).then(() => { // 根據(jù)roles權(quán)限生成可訪問的路由表
router.addRoutes(store.getters.addRouters) // 動(dòng)態(tài)添加可訪問路由表
next({ ...to, replace: true }) // hack方法 確保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
})
}).catch((err) => {
store.dispatch('FedLogOut').then(() => {
Message.error(err || 'Verification failed, please login again')
next({ path: '/' })
})
})
上面的代碼就是vue-element-admin的實(shí)現(xiàn)
缺點(diǎn)
- 全局路由守衛(wèi)里,每次路由跳轉(zhuǎn)都要做判斷
- 菜單信息寫死在前端,要改個(gè)顯示文字或權(quán)限信息,需要重新編譯
- 菜單跟路由耦合在一起,定義路由的時(shí)候還有添加菜單顯示標(biāo)題,圖標(biāo)之類的信息,而且路由不一定作為菜單顯示,還要多加字段進(jìn)行標(biāo)識
菜單與路由分離,菜單由后端返回
菜單的顯示標(biāo)題,圖片等需要隨時(shí)更改,要對菜單做管理功能。
后端直接根據(jù)用戶權(quán)限返回可訪問的菜單。
實(shí)現(xiàn)
前端定義路由信息(標(biāo)準(zhǔn)的路由定義,不需要加其他標(biāo)記字段)。
{
name: "login",
path: "/login",
component: () => import("@/pages/Login.vue")
}
name字段都不為空,需要根據(jù)此字段與后端返回菜單做關(guān)聯(lián)。
做菜單管理功能的時(shí)候,一定要有個(gè)字段與前端的路由的name字段對應(yīng)上(也可以是其他字段,只要菜單能找到對應(yīng)的路由或者路由能找到對應(yīng)的菜單就行),并且做唯一性校驗(yàn)。菜單上還需要定義權(quán)限字段,可以是一個(gè)或多個(gè)。其他信息,比如顯示標(biāo)題,圖標(biāo),排序,鎖定之類的,可以根據(jù)實(shí)際需求進(jìn)行設(shè)計(jì)。

還是在全局路由守衛(wèi)里做判斷
function hasPermission(router, accessMenu) {
if (whiteList.indexOf(router.path) !== -1) {
return true;
}
let menu = Util.getMenuByName(router.name, accessMenu);
if (menu.name) {
return true;
}
return false;
}
Router.beforeEach(async (to, from, next) => {
if (getToken()) {
let userInfo = store.state.user.userInfo;
if (!userInfo.name) {
try {
await store.dispatch("GetUserInfo")
await store.dispatch('updateAccessMenu')
if (to.path === '/login') {
next({ name: 'home_index' })
} else {
//Util.toDefaultPage([...routers], to.name, router, next);
next({ ...to, replace: true })//菜單權(quán)限更新完成,重新進(jìn)一次當(dāng)前路由
}
}
catch (e) {
if (whiteList.indexOf(to.path) !== -1) { // 在免登錄白名單,直接進(jìn)入
next()
} else {
next('/login')
}
}
} else {
if (to.path === '/login') {
next({ name: 'home_index' })
} else {
if (hasPermission(to, store.getters.accessMenu)) {
Util.toDefaultPage(store.getters.accessMenu,to, routes, next);
} else {
next({ path: '/403',replace:true })
}
}
}
} else {
if (whiteList.indexOf(to.path) !== -1) { // 在免登錄白名單,直接進(jìn)入
next()
} else {
next('/login')
}
}
let menu = Util.getMenuByName(to.name, store.getters.accessMenu);
Util.title(menu.title);
});
Router.afterEach((to) => {
window.scrollTo(0, 0);
});
上面代碼是vue-quasar-admin的實(shí)現(xiàn)。因?yàn)闆]有使用addRoutes,每次路由跳轉(zhuǎn)的時(shí)候都要判斷權(quán)限,這里的判斷也很簡單,因?yàn)椴藛蔚膎ame與路由的name是一一對應(yīng)的,而后端返回的菜單就已經(jīng)是經(jīng)過權(quán)限過濾的,所以如果根據(jù)路由name找不到對應(yīng)的菜單,就表示用戶有沒權(quán)限訪問。
如果路由很多,可以在應(yīng)用初始化的時(shí)候,只掛載不需要權(quán)限控制的路由。取得后端返回的菜單后,根據(jù)菜單與路由的對應(yīng)關(guān)系,篩選出可訪問的路由,通過addRoutes動(dòng)態(tài)掛載。
缺點(diǎn)
- 菜單需要與路由做一一對應(yīng),前端添加了新功能,需要通過菜單管理功能添加新的菜單,如果菜單配置的不對會導(dǎo)致應(yīng)用不能正常使用
- 全局路由守衛(wèi)里,每次路由跳轉(zhuǎn)都要做判斷
菜單與路由完全由后端返回
菜單由后端返回是可行的,但是路由由后端返回呢?看一下路由的定義
{
name: "login",
path: "/login",
component: () => import("@/pages/Login.vue")
}
后端如果直接返回
{
"name": "login",
"path": "/login",
"component": "() => import('@/pages/Login.vue')"
}
這是什么鬼,明顯不行。() => import('@/pages/Login.vue')這代碼如果沒出現(xiàn)在前端,webpack不會對Login.vue進(jìn)行編譯打包
實(shí)現(xiàn)
前端統(tǒng)一定義路由組件,比如
const Home = () => import("../pages/Home.vue");
const UserInfo = () => import("../pages/UserInfo.vue");
export default {
home: Home,
userInfo: UserInfo
};
將路由組件定義為這種key-value的結(jié)構(gòu)。
后端返回格式
[
{
name: "home",
path: "/",
component: "home"
},
{
name: "home",
path: "/userinfo",
component: "userInfo"
}
]
在將后端返回路由通過addRoutes動(dòng)態(tài)掛載之間,需要將數(shù)據(jù)處理一下,將component字段換為真正的組件。
至于菜單與路由是否還要分離,怎么對應(yīng),可以根據(jù)實(shí)際需求進(jìn)行處理。
如果有嵌套路由,后端功能設(shè)計(jì)的時(shí)候,要注意添加相應(yīng)的字段。前端拿到數(shù)據(jù)也要做相應(yīng)的處理。
缺點(diǎn)
- 全局路由守衛(wèi)里,每次路由跳轉(zhuǎn)都要做判斷
- 前后端的配合要求更高
不使用全局路由守衛(wèi)
前面幾種方式,除了登錄頁與主應(yīng)用分離,每次路由跳轉(zhuǎn),都在全局路由守衛(wèi)里做了判斷。
實(shí)現(xiàn)
應(yīng)用初始化的時(shí)候只掛載不需要權(quán)限控制的路由
const constRouterMap = [
{
name: "login",
path: "/login",
component: () => import("@/pages/Login.vue")
},
{
path: "/404",
component: () => import("@/pages/Page404.vue")
},
{
path: "/init",
component: () => import("@/pages/Init.vue")
},
{
path: "*",
redirect: "/404"
}
];
export default constRouterMap;
import Vue from "vue";
import Router from "vue-router";
import ConstantRouterMap from "./routers";
Vue.use(Router);
export default new Router({
// mode: 'history', // require service support
scrollBehavior: () => ({ y: 0 }),
routes: ConstantRouterMap
});
登錄成功后跳到/路由
submitForm(formName) {
let _this=this;
this.$refs[formName].validate(valid => {
if (valid) {
_this.$store.dispatch("loginByUserName",{
name:_this.ruleForm2.name,
pass:_this.ruleForm2.pass
}).then(()=>{
_this.$router.push({
path:'/'
})
})
} else {
return false;
}
});
}
因?yàn)楫?dāng)前沒有/路由,會跳到/404
<template>
<h1>404</h1>
</template>
<script>
export default {
name:'page404',
mounted(){
if(!this.$store.state.isLogin){
this.$router.replace({ path: '/login' });
return;
}
if(!this.$store.state.initedApp){
this.$router.replace({ path: '/init' });
return
}
}
}
</script>
404組件里判斷已經(jīng)登錄,接著判斷應(yīng)用是否已經(jīng)初始化(用戶權(quán)限信息,可訪問菜單,路由等是否已經(jīng)從后端取得)。沒有初始化則跳轉(zhuǎn)到/init路由
<template>
<div></div>
</template>
<script>
import { getAccessMenuList } from "../mock/menus";
import components from "../router/routerComponents.js";
export default {
async mounted() {
if (!this.$store.state.isLogin) {
this.$router.push({ path: "/login" });
return;
}
if (!this.$store.state.initedApp) {
const loading = this.$loading({
lock: true,
text: "初始化中",
spinner: "el-icon-loading",
background: "rgba(0, 0, 0, 0.7)"
});
let menus = await getAccessMenuList(); //模擬從后端獲取
var routers = [...menus];
for (let router of routers) {
let component = components[router.component];
router.component = component;
}
this.$router.addRoutes(routers);
this.$store.dispatch("setAccessMenuList", menus).then(() => {
loading.close();
this.$router.replace({
path: "/"
});
});
return;
} else {
this.$router.replace({
path: "/"
});
}
}
};
</script>
init組件里判斷應(yīng)用是否已經(jīng)初始化(避免初始化后,直接從地址欄輸入地址再次進(jìn)入當(dāng)前組件)。
如果已經(jīng)初始化,跳轉(zhuǎn)/路由(如果后端返回的路由里沒有定義次路由,則會跳轉(zhuǎn)404)。
沒有初始化,則調(diào)用遠(yuǎn)程接口獲取菜單和路由等,然后處理后端返回的路由,將component賦值為真正
的組件,接著調(diào)用addRoutes掛載新路由,最后跳轉(zhuǎn)/路由即可。菜單的處理也是在此處,看實(shí)際
需求。
缺點(diǎn)
- 在404頁面做了判斷,感覺比較怪異
- 多引入了一個(gè)init頁面組件
總結(jié)
比較推薦后面兩種實(shí)現(xiàn)方式。
好了,以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
- vue addRoutes實(shí)現(xiàn)動(dòng)態(tài)權(quán)限路由菜單的示例
- Vue 權(quán)限控制的兩種方法(路由驗(yàn)證)
- 關(guān)于Vue的路由權(quán)限管理的示例代碼
- vue iview實(shí)現(xiàn)動(dòng)態(tài)路由和權(quán)限驗(yàn)證功能
- vue 設(shè)置路由的登錄權(quán)限的方法
- vue實(shí)現(xiàn)權(quán)限控制路由(vue-router 動(dòng)態(tài)添加路由)
- vue-router 控制路由權(quán)限的實(shí)現(xiàn)
- vue2/vue3路由權(quán)限管理的方法實(shí)例
相關(guān)文章
利用Vue3+Element?Plus封裝公共表格組件(帶源碼)
最近公司項(xiàng)目中頻繁會使用到table表格,而且前端技術(shù)這一塊也用到了vue3來開發(fā),所以基于element plus table做了一個(gè)二次封裝的組件,這篇文章主要給大家介紹了關(guān)于利用Vue3+Element?Plus封裝公共表格組件的相關(guān)資料,需要的朋友可以參考下2023-11-11
關(guān)于vue-router路由的傳參方式params query
這篇文章主要介紹了關(guān)于vue-router路由的傳參方式params query,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-10-10
vue2.x版本中computed和watch的使用及關(guān)聯(lián)和區(qū)別
這篇文章主要介紹了vue2.x版本中computed和watch的使用及關(guān)聯(lián)和區(qū)別,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,需要的小伙伴可以參考一下2022-07-07
vue跳轉(zhuǎn)時(shí)根據(jù)url錨點(diǎn)(#xxx)實(shí)現(xiàn)頁面內(nèi)容定位的方法
本前端仔在做頁面跳轉(zhuǎn)的時(shí)候,被要求跳轉(zhuǎn)到頁面時(shí)候,把對應(yīng)部分的內(nèi)容自動(dòng)滾動(dòng)到頂部,我一開始想到的就是根據(jù)錨點(diǎn)<a href="#xxid">進(jìn)行處理,但是發(fā)現(xiàn)不太好實(shí)現(xiàn),于是便自己研究了一個(gè)比較取巧的方法,需要的朋友可以參考下2024-04-04
vue解決刷新頁面時(shí)會出現(xiàn)變量閃爍的問題
這篇文章主要介紹了vue解決刷新頁面時(shí)會出現(xiàn)變量閃爍的問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01
element表單使用校驗(yàn)之校驗(yàn)失效問題詳解
最近工作中遇到了element表單校驗(yàn)失敗的情況,通過查找相關(guān)資料終于解決了,所以下面這篇文章主要給大家介紹了關(guān)于element表單使用校驗(yàn)之校驗(yàn)失效問題的相關(guān)資料,需要的朋友可以參考下2022-10-10

