使用全局路由守衛
實現
前端定義好路由,並且在路由上標記相應的權限信息
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
}
}]
}]
全局路由守衛每次都判斷用戶是否已經登錄,沒有登錄則跳到登錄頁。已經登錄(已經取得后台返回的用戶的權限信息(角色之類的)),則判斷當前要跳轉的路由,用戶是否有權限訪問(根據路由名稱到全部路由里找到對應的路由,判斷用戶是否具備路由上標注的權限信息(比如上面的roles: ['admin', 'editor']
))。沒有權限則跳到事先定義好的界面(403,404之類的)。
這種方式,菜單可以直接用路由生成(用戶沒有權限的菜單也會顯示,點擊跳轉的時候才做權限判斷),也可以在用戶登錄后根據用戶權限把路由過濾一遍生成菜單(菜單需要保存在vuex里)。
目前iview-admin還是用的這種方式
缺點
- 加載所有的路由,如果路由很多,而用戶並不是所有的路由都有權限訪問,對性能會有影響。
- 全局路由守衛里,每次路由跳轉都要做權限判斷。
- 菜單信息寫死在前端,要改個顯示文字或權限信息,需要重新編譯
- 菜單跟路由耦合在一起,定義路由的時候還有添加菜單顯示標題,圖標之類的信息,而且路由不一定作為菜單顯示,還要多加字段進行標識
登錄頁與主應用分離
針對前一種實現方式的缺點,可以將登錄頁與主應用放到不同的頁面(不在同一個vue應用實例里)。
實現
登錄成功后,進行頁面跳轉(真正的頁面跳轉,不是路由跳轉),並將用戶權限傳遞到主應用所在頁面,主應用初始化之前,根據用戶權限篩選路由,篩選后的路由作為vue的實例化參數,而不是像前一種方式所有的路由都傳遞進去,也不需要在全局路由守衛里做權限判斷了。
缺點
- 需要做頁面跳轉,不是純粹的單頁應用
- 菜單信息寫死在前端,要改個顯示文字或權限信息,需要重新編譯
- 菜單跟路由耦合在一起,定義路由的時候還有添加菜單顯示標題,圖標之類的信息,而且路由不一定作為菜單顯示,還要多加字段進行標識
使用addRoutes
動態掛載路由
addRoutes
允許在應用初始化之后,動態的掛載路由。有了這個新姿勢,就不用像前一種方式那樣要在應用初始化之要對路由進行篩選。
實現
應用初始化的時候先掛載不需要權限控制的路由,比如登錄頁,404等錯誤頁。
有個問題,addRoutes
應該何時調用,在哪里調用
登錄后,獲取用戶的權限信息,然后篩選有權限訪問的路由,再調用addRoutes
添加路由。這個方法是可行的。但是不可能每次進入應用都需要登錄,用戶刷新瀏覽器又要登陸一次。
所以addRoutes
還是要在全局路由守衛里進行調用
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) { // 判斷當前用戶是否已拉取完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(() => { // 根據roles權限生成可訪問的路由表
router.addRoutes(store.getters.addRouters) // 動態添加可訪問路由表
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 {
// 沒有動態改變權限的需求可直接next() 刪除下方權限判斷 ↓
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) { // 在免登錄白名單,直接進入
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
})
關鍵的代碼如下
if (store.getters.roles.length === 0) { // 判斷當前用戶是否已拉取完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(() => { // 根據roles權限生成可訪問的路由表
router.addRoutes(store.getters.addRouters) // 動態添加可訪問路由表
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的實現
缺點
- 全局路由守衛里,每次路由跳轉都要做判斷
- 菜單信息寫死在前端,要改個顯示文字或權限信息,需要重新編譯
- 菜單跟路由耦合在一起,定義路由的時候還有添加菜單顯示標題,圖標之類的信息,而且路由不一定作為菜單顯示,還要多加字段進行標識
菜單與路由分離,菜單由后端返回
菜單的顯示標題,圖片等需要隨時更改,要對菜單做管理功能。
后端直接根據用戶權限返回可訪問的菜單。
實現
前端定義路由信息(標准的路由定義,不需要加其他標記字段)。
{
name: "login",
path: "/login",
component: () => import("@/pages/Login.vue")
}
name字段都不為空,需要根據此字段與后端返回菜單做關聯。
做菜單管理功能的時候,一定要有個字段與前端的路由的name字段對應上(也可以是其他字段,只要菜單能找到對應的路由或者路由能找到對應的菜單就行),並且做唯一性校驗。菜單上還需要定義權限字段,可以是一個或多個。其他信息,比如顯示標題,圖標,排序,鎖定之類的,可以根據實際需求進行設計。

image
還是在全局路由守衛里做判斷
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 })//菜單權限更新完成,重新進一次當前路由
}
}
catch (e) {
if (whiteList.indexOf(to.path) !== -1) { // 在免登錄白名單,直接進入
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) { // 在免登錄白名單,直接進入
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的實現。因為沒有使用addRoutes
,每次路由跳轉的時候都要判斷權限,這里的判斷也很簡單,因為菜單的name與路由的name是一一對應的,而后端返回的菜單就已經是經過權限過濾的,所以如果根據路由name找不到對應的菜單,就表示用戶有沒權限訪問。
如果路由很多,可以在應用初始化的時候,只掛載不需要權限控制的路由。取得后端返回的菜單后,根據菜單與路由的對應關系,篩選出可訪問的路由,通過addRoutes
動態掛載。
缺點
- 菜單需要與路由做一一對應,前端添加了新功能,需要通過菜單管理功能添加新的菜單,如果菜單配置的不對會導致應用不能正常使用
- 全局路由守衛里,每次路由跳轉都要做判斷
菜單與路由完全由后端返回
菜單由后端返回是可行的,但是路由由后端返回呢?看一下路由的定義
{
name: "login",
path: "/login",
component: () => import("@/pages/Login.vue")
}
后端如果直接返回
{
"name": "login",
"path": "/login",
"component": "() => import('@/pages/Login.vue')"
}
這是什么鬼,明顯不行。() => import('@/pages/Login.vue')
這代碼如果沒出現在前端,webpack不會對Login.vue
進行編譯打包
實現
前端統一定義路由組件,比如
const Home = () => import("../pages/Home.vue");
const UserInfo = () => import("../pages/UserInfo.vue");
export default {
home: Home,
userInfo: UserInfo
};
將路由組件定義為這種key-value的結構。
后端返回格式
[
{
name: "home",
path: "/",
component: "home"
},
{
name: "home",
path: "/userinfo",
component: "userInfo"
}
]
在將后端返回路由通過addRoutes
動態掛載之間,需要將數據處理一下,將component字段換為真正的組件。
至於菜單與路由是否還要分離,怎么對應,可以根據實際需求進行處理。
如果有嵌套路由,后端功能設計的時候,要注意添加相應的字段。前端拿到數據也要做相應的處理。
缺點
- 全局路由守衛里,每次路由跳轉都要做判斷
- 前后端的配合要求更高
不使用全局路由守衛
前面幾種方式,除了登錄頁與主應用分離
,每次路由跳轉,都在全局路由守衛里做了判斷。
實現
應用初始化的時候只掛載不需要權限控制的路由
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;
}
});
}
因為當前沒有/
路由,會跳到/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組件里判斷已經登錄,接着判斷應用是否已經初始化(用戶權限信息,可訪問菜單,路由等是否已經從后端取得)。沒有初始化則跳轉到/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組件里判斷應用是否已經初始化(避免初始化后,直接從地址欄輸入地址再次進入當前組件)。
如果已經初始化,跳轉/
路由(如果后端返回的路由里沒有定義次路由,則會跳轉404)。
沒有初始化,則調用遠程接口獲取菜單和路由等,然后處理后端返回的路由,將component賦值為真正
的組件,接着調用addRoutes
掛載新路由,最后跳轉/
路由即可。菜單的處理也是在此處,看實際
需求。
缺點
- 在404頁面做了判斷,感覺比較怪異
- 多引入了一個init頁面組件
總結
比較推薦后面兩種實現方式。