1.下载异步加载插件
npm install babel-plugin-syntax-dynamic-import@6.18.0 -D
或者npm install babel-plugin-syntax-dynamic-import@6.18.0 --save--dev //插件依赖
//.babelrc 文件夹中增加
"plugins": [
"syntax-dynamic-import"
],
iview-admin2.0中实现的:https://github.com/iview/iview-admin.git
// 动态路由函数()
export let initroute = function(arr) {
// arr 后台返回的路由数组
let routes = arr.map((item, index) => {
// 整理成自己的路由格式
return {
// 路由路径
path: item.webPath,
// 路由别名
name: item.name,
// 携带参数
meta: {
icon: item.icon,
title: item.description
},
// 组件
component: Main,
children: item.children.map((oitem, index) => {
// 不规则路由处理
if (oitem.component.indexOf("_c") != -1) {
// 消除路由多余字符串
oitem.component = oitem.component.replace("_c/cwl", "");
return {
path: oitem.webPath,
name: oitem.name,
meta: {
icon: item.icon,
title: oitem.description
},
// 动态路由增加 (webpack 不能完全动态增加路径 因此只能使用拼接路径 坑拼接2个文件夹 不然那报错)
component: () => import(`_c/cwl${oitem.component}`)
};
}
})
};
});
return routes;
};
实现思路
1.登录是将路由添加到路由 并缓存到本地
// route对象
import router from "@/router";
// routes 数组
import routes from "@/router/routers.js";
//方法
handleSubmit({ userName, password }) {
password = md5(password);
this.handleLogin({ userName, password }).then((res) => {
if (!res.success) {
// 登录
this.message = res.respDesc;
} else {
this.getUserInfo().then((res) => {
// this.$router.push({
// name: this.$config.homeName,
// });
//添加路由
this.addrout().then((response) => {
// 路由数据
sessionStorage.setItem("routelist", response.respBody);
let routingArray = initroute(JSON.parse(response.respBody));
routes.push(...routingArray);
router.addRoutes(routes);
this.$router.push({
name: this.$config.homeName,
});
// this.getUserInfo().then((res) => {
// console.log(res, "===123");
// this.$router.push({
// name: this.$config.homeName,
// });
// });
});
});
}
});
},
2.路由刷新 取出缓存 在router.beforeEach中添加
import { initroute } from "@/libs/initroute";
//取出缓存
let routelist =sessionStorage.getItem("routelist");
// 判断缓存是否有 是否已经添加过
if(routelist&&routes.length<6){
let routelist = sessionStorage.getItem("routelist");
let routingArray = initroute(JSON.parse(routelist));
routes.push(...routingArray);
router.addRoutes(routes);
}
router.beforeEach((to, from, next) => {
iView.LoadingBar.start();
const token = getToken();
if (!token && to.name !== LOGIN_PAGE_NAME) {
// 未登录且要跳转的页面不是登录页
next({
name: LOGIN_PAGE_NAME // 跳转到登录页
});
} else if (!token && to.name === LOGIN_PAGE_NAME) {
// 未登陆且要跳转的页面是登录页
next(); // 跳转
} else if (token && to.name === LOGIN_PAGE_NAME) {
// 已登录且要跳转的页面是登录页
next({
name: homeName // 跳转到homeName页
});
} else {
if (store.state.user.hasGetInfo) {
turnTo(to, store.state.user.access, next);
console.log(to, "====456");
} else {
store
.dispatch("getUserInfo")
.then(user => {
// 拉取用户信息,通过用户权限和跳转的页面的name来判断是否有权限访问;access必须是一个数组,如:['super_admin'] ['super_admin', 'admin']
turnTo(to, user.access, next);
console.log(to, "====123");
})
.catch(() => {
setToken("");
next({
name: "login"
});
});
}
}
});