特别注意,原配置中的*配置要注释或删除,否则后续配置完成后动态菜单刷新会报404错误,该配置需要在addRoutes添加,见后续说明
修改getInfo方法,获取菜单数据并保存到vuex中;同时还需后端java接口做好了菜单数据准备
注:如果后端没准备好,这里menus可以先直接定义数组测试,参考数组
[{ "component": "Layout", "path": "/user", "redirect": "/user/list", "name": "userManage", "meta": { "icon": "userManage", "title": "用户管理" }, "children": [{ "component": "user/user", "path": "list", "name": "userList", "meta": { "icon": "userList", "title": "用户列表" } }, { "component": "user/role", "path": "role", "name": "roleList", "meta": { "icon": "role", "title": "角色列表" } }, { "component": "user/permission", "path": "permission", "name": "permissionList", "meta": { "icon": "permission", "title": "权限列表" } }] }]
根据环境配置导入组件,在vue中,将菜单路径作为参数,实现路由地址的注入
在 src/router 文件夹下,建立两个文件,各只需添加一行代码, 定义导入方法
src/router/_import_development.js
//开发环境导入组件 module.exports = file => require('@/views/' + file + '.vue').default
src/router/_import_production.js
//生产环境导入组件 module.exports = file => () => import('@/views/' + file + '.vue')
特别注意:上述路径views后面不要遗漏斜杠
在路由钩子中,过滤路由,并生成路由,核心在src目录下的permission.js中,修改router.beforeEach路由钩子
关键代码:
import Layout from '@/layout' const _import = require('@/router/_import_' + process.env.NODE_ENV)
// 1.过滤路由 const menus = filterAsyncRouter(store.getters.menus) // 2.将*配置直接加载到动态路由,避免404 menus.push({ path: "*", redirect: "/404" }); // 2.动态添加路由 router.addRoutes(menus) // 3.将路由数据传递给全局变量 global.antRouter = menus next({ ...to, replace: true })
// 遍历后台传来的路由字符串,转换为组件对象 function filterAsyncRouter(asyncRouterMap) { const accessedRouters = asyncRouterMap.filter(route => { if (route.component) { if (route.component === '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 }