前端定義好路由,而且在路由上標記相應的權限信息css
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裏)。vue
目前iview-admin仍是用的這種方式webpack
加載全部的路由,若是路由不少,而用戶並非全部的路由都有權限訪問,對性能會有影響。git
全局路由守衛裏,每次路由跳轉都要作權限判斷。github
菜單信息寫死在前端,要改個顯示文字或權限信息,須要從新編譯web
菜單跟路由耦合在一塊兒,定義路由的時候還有添加菜單顯示標題,圖標之類的信息,並且路由不必定做爲菜單顯示,還要多加字段進行標識vue-router
針對前一種實現方式的缺點,能夠將登陸頁與主應用放到不一樣的頁面(不在同一個vue應用實例裏)。vuex
登陸成功後,進行頁面跳轉(真正的頁面跳轉,不是路由跳轉),並將用戶權限傳遞到主應用所在頁面,主應用初始化以前,根據用戶權限篩選路由,篩選後的路由做爲vue的實例化參數,而不是像前一種方式全部的路由都傳遞進去,也不須要在全局路由守衛裏作權限判斷了。element-ui
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字段對應上(也能夠是其餘字段,只要菜單能找到對應的路由或者路由能找到對應的菜單就行),而且作惟一性校驗。菜單上還須要定義權限字段,能夠是一個或多個。其餘信息,好比顯示標題,圖標,排序,鎖定之類的,能夠根據實際需求進行設計。
仍是在全局路由守衛裏作判斷
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
掛載新路由,最後跳轉/
路由便可。菜單的處理也是在此處,看實際 需求。
比較推薦後面兩種實現方式。