最近做的后台管理項目,頁面路由是單獨有一個操作頁面管理,增加修改刪除,所以路由就需要做成動態的.由后台保存,登錄時獲取加載,這里把方法記錄下來
這里用的項目代碼是git上一位大神的項目,GitHub地址:https://github.com/PanJiaChen/vue-element-admin,是一個很優秀的后台管理項目,大家可以下載下來看下
動態路由主要是兩點,一是需要從后台獲取路由,二是在什么時候把異步獲取的路由添加進去
需要改動的文件,以這個項目目錄為例
router>index.js
import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) /* Layout */ import Layout from '@/layout' // 靜態路由,這里寫好一些不需要從后台獲取的路由,如首頁,404頁面 export const constantRoutes = [ { path: '/login', component: () => import('@/views/login/index'), hidden: true }, { path: '/404', component: () => import('@/views/error-page/404'), hidden: true } .... ] const createRouter = () => new Router({ scrollBehavior: () => ({ y: 0 }), routes: constantRoutes }) const router = createRouter() // 重置路由 export function resetRouter() { const newRouter = createRouter() router.matcher = newRouter.matcher // reset router } export default router
一般把獲取路由,路由的方法放在vuex中
store>modules>permission.js
import { constantRoutes } from '@/router'
import { getRoutes } from '@/api/role' // 獲取路由的接口方法
import Layout from '@/layout'
/**
* Use meta.role to determine if the current user has permission
* @param roles
* @param route
*/
function hasPermission(roles, route) {
if (route.meta && route.meta.roles) {
return roles.some(role => route.meta.roles.includes(role))
} else {
return true
}
}
/**
* 把后台返回菜單組裝成routes要求的格式
* @param {*} routes
*/
export function getAsyncRoutes(routes) {
const res = []
const keys = ['path', 'name', 'children', 'redirect', 'alwaysShow', 'meta', 'hidden']
routes.forEach(item => {
const newItem = {}
if (item.component) {
if (item.component === 'layout/Layout') {
newItem.component = Layout
} else {
newItem.component = () => import(`@/${item.component}`)
}
}
for (const key in item) {
if (keys.includes(key)) {
newItem[key] = item[key]
}
}
if (newItem.children && newItem.children.length) {
newItem.children = getAsyncRoutes(item.children)
}
res.push(newItem)
})
return res
}
/**
* Filter asynchronous routing tables by recursion
* @param routes asyncRoutes
* @param roles
*/
export function filterAsyncRoutes(routes, roles) {
const res = []
routes.forEach(route => {
const tmp = { ...route }
if (hasPermission(roles, tmp)) {
if (tmp.children) {
tmp.children = filterAsyncRoutes(tmp.children, roles)
}
res.push(tmp)
}
})
return res
}
const state = {
routes: [],
addRoutes: []
}
const mutations = {
SET_ROUTES: (state, routes) => {
state.addRoutes = routes
state.routes = constantRoutes.concat(routes)
}
}
const actions = {
generateRoutes({ commit }, roles) {
return new Promise(async resolve => {
let accessedRoutes
const routes = await getRoutes() // 獲取到后台路由
const asyncRoutes = getAsyncRoutes(routes.data) // 對路由格式進行處理
console.log(33, routes, asyncRoutes)
if (roles.includes('admin')) {
accessedRoutes = asyncRoutes || []
} else { // 這里是有做權限過濾的,如果不需要就不用
accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
}
commit('SET_ROUTES', accessedRoutes)
resolve(accessedRoutes)
})
}
}
export default {
namespaced: true,
state,
mutations,
actions
}
拿到異步路由后,需要在路由攔截中加入
permission.js
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' // get token from cookie import getPageTitle from '@/utils/get-page-title' NProgress.configure({ showSpinner: false }) // NProgress Configuration const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist router.beforeEach(async(to, from, next) => { // start progress bar NProgress.start() // set page title document.title = getPageTitle(to.meta.title) // determine whether the user has logged in const hasToken = getToken() if (hasToken) { if (to.path === '/login') { // if is logged in, redirect to the home page next({ path: '/' }) NProgress.done() } else { // determine whether the user has obtained his permission roles through getInfo const hasRoles = store.getters.roles && store.getters.roles.length > 0 if (hasRoles) { next() } else { try { // get user info // note: roles must be a object array! such as: ['admin'] or ,['developer','editor'] const { roles } = await store.dispatch('user/getInfo') // 在這里獲取異步路由 const accessRoutes = await store.dispatch('permission/generateRoutes', roles) // 調用router.addRoutes方法,將異步路由添加進去 router.addRoutes(accessRoutes) // console.log(44, router) // hack method to ensure that addRoutes is complete // set the replace: true, so the navigation will not leave a history record next({ ...to, replace: true }) } catch (error) { // remove token and go to login page to re-login await store.dispatch('user/resetToken') Message.error(error || 'Has Error') next(`/login?redirect=${to.path}`) NProgress.done() } } } } else { /* has no token*/ if (whiteList.indexOf(to.path) !== -1) { // in the free login whitelist, go directly next() } else { // other pages that do not have permission to access are redirected to the login page. next(`/login?redirect=${to.path}`) NProgress.done() } } }) router.afterEach(() => { // finish progress bar NProgress.done() })
后台接口數據(這個項目是用mock模擬的,實際你替換一下接口地址就行)
后台的數據格式參考這個格式
export const asyncRoutes = [ { path: '/permission', component: 'layout/Layout', redirect: '/permission/index', alwaysShow: true, meta: { title: 'Permission', icon: 'lock', roles: ['admin', 'editor'] }, children: [ { path: 'page', component: 'views/permission/page', name: 'PagePermission', meta: { title: 'Page Permission', roles: ['admin'] } }, { path: 'directive', component: 'views/permission/directive', name: 'DirectivePermission', meta: { title: 'Directive Permission' } }, { path: 'role', component: 'views/permission/role', name: 'RolePermission', meta: { title: 'Role Permission', roles: ['admin'] } } ] }, { path: '/icon', component: 'layout/Layout', children: [ { path: 'index', component: 'views/icons/index', name: 'Icons', meta: { title: 'Icons', icon: 'icon', noCache: true } } ] } ]
這個文件改下,之前返回的是全部的路由,現在只需要異步路由
mock>role>index.js
export default [ // mock get all routes form server { url: '/vue-element-admin/routes', type: 'get', response: _ => { return { code: 20000, data: asyncRoutes } } } ]
到這里就OK了,總結一下:
1. 路由文件中把需要從后台獲取的路由都刪除,只留下靜態路由
2. 在vuex中定義一個路由模塊,state存放路由,action獲取路由,將獲取路由的方法放在actions中
3. 在路由攔截router.beforeEach方法中,調用vuex中的獲取路由方法拿到異步路由,調用router.addRoutes方法,將異步路由添加進去
這里補充一下,使用這個項目添加動態路由時由於babel-eslint的版本問題,不支持newItem.component = () => import(`@/${item.component}`)這種寫法,頁面空白,控制台報錯
Module build failed (from ./node_modules/_eslint-loader@2.2.1@eslint-loader/index.js): TypeError: Cannot read property 'range' of null
我把這個版本改成推薦的穩定版7.2.3之后就可以了
你們可以直接修改package包的版本后再install,不然刪包之后再下載可能有緩存,我就是這樣,一番折騰
