路由懒加载的目的,避免单页面应用一次性加载时间
import Vue from 'vue';
import Router from 'vue-router';
Vue.use(Router);
// 路由配置
let router = new Router({
mode: 'history',
routes: [{
path: '/',
// component: login
component: resolve => require(['@/pages/login'], resolve),
name: 'Login'
}]
});
export default router;
偶现 Loading chunk {n} failed 错误,导致页面不能切换
解决方法: 运用vue-router的错误处理函数 onError 捕获错误,代码如下:
router.onError((error) => {
const pattern = /Loading chunk (\d)+ failed/g;
const isChunkLoadFailed = error.message.match(pattern);
const targetPath = router.history.pending.fullPath;
if (isChunkLoadFailed) {
router.replace(targetPath);
}
});