login.vue
setTimeout(() => { this.isLoading = false; if (this.userInfo.name == 'admin' && this.userInfo.pwd == '123456') { Cookies.set('user', 'a'); Cookies.set('teRout', JSON.stringify(teRout)); let sk = filterAsyncRouter(teRout); let newRoutes = constantRouterMap.concat(sk); this.$router.addRoutes(sk); this.$router.push({ path: '/' }); } else { this.$notify.error({ title: '错误', message: '请输入正确的账户密码' }); } }, 100);
teRout.json
[ { "path": "/", "name": "Home", "component": "Home" }, { "path": "/about", "name": "about", "component": "About" } ]
router/rule.js
const _import = require('./_import_' + process.env.NODE_ENV); //获取组件的方法 export function filterAsyncRouter(asyncRouterMap) { let sc = JSON.parse(JSON.stringify(asyncRouterMap)); //遍历后台传来的路由字符串,转换为组件对象 const accessedRouters = sc.filter(route => { if (route.component) { route.component = _import(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; }
_import_development.js
module.exports = file => require('@/views/' + file + '.vue').default // vue-loader at least v13.0.0+
_import_production.js
module.exports = file => () => import('@/views/' + file + '.vue')
router/index.js
//https://www.php.cn/js-tutorial-406277.html import Vue from 'vue'; import VueRouter from 'vue-router'; import routes from './router'; import Cookies from 'js-cookie'; import { filterAsyncRouter } from './rule'; import tools from '@/utils/tools'; import topbar from '@/utils/topbar'; Vue.use(VueRouter); const router = new VueRouter({ routes }); router.beforeEach((to, from, next) => { if (localStorage.getItem('new')) { var c = JSON.parse(localStorage.getItem('new')), lastUrl = getLastUrl(window.location.href, '/'); if (c.path == lastUrl) { //动态路由页面的刷新事件 let newRoutes = constantRouterMap.concat([ { path: c.path, component: resolve => require(['@/components/' + c.component + ''], resolve) } ]); localStorage.removeItem('new'); router.addRoutes(newRoutes); router.replace(c.path); //replace,保证浏览器回退的时候能直接返回到上个页面,不会叠加 } } next(); }); var getLastUrl = (str, yourStr) => str.slice(str.lastIndexOf(yourStr)); //取到浏览器出现网址的最后"/"出现的后边的字符 export const constantRouterMap = routes; export default router;
总结: 1>动态路由addRoutes添加需要在vue文件中进行,在路由守卫中搞容易死循环
2>后台传来的路由数组肯定都是字符串,特别注意
"component": "Home",这个Home得是个路径,不能是字符串,所以需要
filterAsyncRouter这个函数去转化,所以组件建的路径很重要