示例选用的iview-admin实现,store存数据刷新要丢失,可以使用lowdb插件本地存储。
1.后台返回的路由数据格式化
component里面是view文件的路径地址
let menu = [{
path: '/',
name: '_home',
redirect: '/home',
type: 'menu',
component: 'Main',
meta: {
hideInMenu: true,
notCache: true
},
children: [
{
path: '/home',
name: 'home',
type: 'menu',
meta: {
hideInMenu: true,
title: '首页',
notCache: true,
icon: 'md-home'
},
component: '/single-page/home'
}
]
},
{
path: '',
name: 'doc',
type: 'blank',
meta: {
title: '新页签打开路由',
icon: 'ios-book'
},
component: '/blank'
},
{
path: '',
name: 'doc',
type: 'inHref',
meta: {
title: '外部链接',
href: 'https://lison16.github.io/iview-admin-doc/#/',
icon: 'ios-book'
},
component: '/Frame'
},
{
path: '/update',
name: 'update',
type: 'menu',
meta: {
icon: 'md-cloud-upload',
title: '数据上传'
},
component: 'Main',
children: [
{
path: 'update_table_page',
name: 'update_table_page',
meta: {
icon: 'ios-document',
title: '上传Csv'
},
type: 'menu',
component: '/update/update-table'
},
{
path: 'update_paste_page',
name: 'update_paste_page',
meta: {
icon: 'md-clipboard',
title: '粘贴表格数据'
},
type: 'menu',
component: '/update/update-paste'
}
]
}]
2.新建文件_import_development.js将菜单数据转换成路由需要的文件路径格式
module.exports = file => () => import('@/view' + file + '/index.vue')
3.使用filterAsyncRouter方法,将后端返回的路由改为路由需要的数据
import _import from '@/router/_import_development.js'
import Main from '@/components/main/index.vue' // Layout 是架构组件,不在后台返回,在文件里单独引入
import Frame from '@/view/frame/index.vue'
export const filterAsyncRouter = (asyncRouterMap, parentName, router) => { // 遍历后台传来的路由字符串,转换为组件对象
const accessedRouters = asyncRouterMap.filter(route => {
if (route.component) {
if (route.component === 'Main') { // Layout组件特殊处理
route.component = Main
} else if (route.type && route.type === 'inHref') {
// 内嵌外链的方式
route.component = Frame
route.meta.frame = 'inside'
} else {
route.component = _import(route.component)
// 新页签打开内部路由
if (route.type && route.type === 'blank') {
route.meta.frame = 'blank'
}
}
router.addRoute(parentName || '', {
path: route.path,
component: route.component,
name: route.name,
redirect: route.redirect,
meta: route.meta
})
}
if (route.children && route.children.length) {
route.children = filterAsyncRouter(route.children, route.name, router)
}
return true
})
return accessedRouters
}
注意:这里添加路由是嵌套路由,不然没有框架,没法切换菜单
4.路由next()
5.在登录的时候调用获取菜单接口,调用filterAsyncRouter方法,存储菜单,在菜单栏使用
// 动态创建菜单,存入store里面
let menuSider = filterAsyncRouter(menu, '', router)
commit('setMenuList', menuSider, { root: true })