1 在路由实例中保留公共基础路由
export const constantRoutes = [{
path: '/redirect',
component: Layout,
hidden: true,
children: [{
path: '/redirect/:path(.*)',
component: () => import('@/views/redirect/index')
}]
},
{
path: '/login',
component: () => import('@/views/login/index'),
hidden: true
},
{
path: '/auth-redirect',
component: () => import('@/views/login/auth-redirect'),
hidden: true
},
{
path: '/404',
component: () => import('@/views/error-page/404'),
hidden: true
},
{
path: '/401',
component: () => import('@/views/error-page/401'),
hidden: true
},
2 vuex -> user -> getInfo 获取菜单信息
// get user info
getInfo({
commit,
state
}) {
return new Promise((resolve, reject) => {
getInfo().then(response => {
const {
result
} = response
if (!result) {
reject('信息验证失败,请稍后再试!')
}
const {
id,
// roles,
username,
// avatar,
introduction
} = result
commit('SET_ID', id)
commit('SET_ROLES', ['admin'])
commit('SET_NAME', username)
// commit('SET_AVATAR', avatar)
commit('SET_INTRODUCTION', introduction ? introduction : []) //菜单信息
result.roles = ['admin']
resolve(result)
}).catch(error => {
reject(error)
})
})
},
3.动态生成权限路由方法(核心)
根据环境配置导入组件,在vue中,将菜单路径作为参数,实现路由地址的注入
在 src/router 文件夹下,建立两个文件,各只需添加一行代码, 定义导入方法
src/router/_import_development.js
//开发环境导入组件
module.exports = file => require('@/views/' + file).default // vue-loader at least v13.0.0+
src/router/_import_production.js
//开发环境导入组件
module.exports = file => require('@/views/' + file).default // vue-loader at least v13.0.0+
在utils目录下创建 filterAsyncRouter.js
/* Layout */
import Layout from '@/layout'
const _import = require('@/router/_import_' + process.env.NODE_ENV) // 获取组件的方法
function filterAsyncRouter(asyncRouterMap) { //遍历后台传来的路由字符串,转换为组件对象
const accessedRouters = asyncRouterMap.filter(route => {
if (route.component) {
if (route.component === 'Layout') { //Layout组件特殊处理
route.component = Layout
} else {
route.component = _import(route.component) // 导入组件
}
}
if (route.children && route.children.length) {
route.children = filterAsyncRouter(route.children)
}
return true
})
return accessedRouters
}
export default filterAsyncRouter
4 在src/permission.js 引入filterAsyncRouter,将菜单信息过滤生成路由,部分代码:
import filterAsyncRouter from '@/utils/filterAsyncRouter'
let accessedRoutes = filterAsyncRouter(introduction)
const accessRoutes = await store.dispatch('permission/generateRoutes', accessedRoutes)
// dynamically add accessible routes
router.addRoutes(accessRoutes)
修改 vuex->permission->generateRoutes方法
generateRoutes({ commit }, accessedRoutes) {
return new Promise(resolve => {
commit('SET_ROUTES', accessedRoutes)
resolve(accessedRoutes)
})
}