依照
iView-admin2.0动态菜单路由【版1】 归纳几个节点
动态路由获取方式2 ——> easymock假数据 ——> 数据转组件处理、addRoutes ——> localStorage存储 ——> 动态路由path刷新
修改操作--关于动态路由
1. 删掉src/main.js中mounted调用的初始化动态路由函数initRouter()——————即没做修改的初状态写法即可 ,【版1】去掉修改src/main.js的步骤
2.新增src/libs/router-util.js做请求动态路由的数据处理,转为路由组件,commit更新updateMenuList[写在src/store/module/app.js]左侧菜单并addRoutes到路由表
![]()
/**
* ①添
* @@新增 定义初始化菜单
*/
import { getToken, localSave, localRead } from '@/libs/util'
// import config from '@/config'
import store from '@/store'
import { lazyLoadingCop } from '@/libs/tools'
import { mockAntRouter } from '@/api/mockApi'
import Main from '@/components/main' // Main 是架构组件,不在后台返回,在文件里单独引入
import parentView from '@/components/parent-view' // parentView 是二级架构组件,不在后台返回,在文件里单独引入
// const _import = require('@/router/_import_' + process.env.NODE_ENV)// 获取组件的方法
var gotRouter
// 初始化路由
export const initRouter = () => {
let antRouter = localRead('dynamicRouter');
if (!antRouter) {
mockAntRouter().then(res => {
if (res.status === 200) {
var routerData = res.data.router // 后台拿到路由
localSave('dynamicRouter', JSON.stringify(routerData)) // 存储路由到localStorage
gotRouter = filterAsyncRouter(routerData) // 过滤路由,路由组件转换
store.commit('updateMenuList', gotRouter);
dynamicRouterAdd()
} else {
console.log('请求失败')
}
})
} else {
gotRouter = dynamicRouterAdd()
}
return gotRouter
}
// 加载路由菜单,从localStorage拿到路由,在创建路由时使用
export const dynamicRouterAdd = () => {
let dynamicRouter = []
let data = localRead('dynamicRouter')
if (!data) {
return dynamicRouter
}
dynamicRouter = filterAsyncRouter(JSON.parse(data))
return dynamicRouter
}
// @函数: 遍历后台传来的路由字符串,转换为组件对象
export const filterAsyncRouter = (asyncRouterMap) => {
const accessedRouters = asyncRouterMap.filter(route => {
if (route.component) {
if (route.component === 'Main') { // Main组件特殊处理
route.component = Main
} else if (route.component === 'parentView') { // parentView组件特殊处理
route.component = parentView
} else {
// route.component = _import(route.component)
route.component = lazyLoadingCop(route.component)
}
}
if (route.children && route.children.length) {
route.children = filterAsyncRouter(route.children)
}
return true
})
return accessedRouters
}
View Code