懶加載
懶加載:避免單頁面應用一次性加載全部組件造成加載時間過長。
使用:
// router文件中
routes: [
{
path: '/Login',
name: 'Login',
component: resolve => require(['@/views/Login'], resolve)
}
...
]
跳轉或加載路由時報錯 Loading chunk {n} failed
使用懶加載會經常導致導航點擊沒用,加載模塊出現錯誤
解決:在當前文件中加入vue-routerrouter的錯誤處理函數onError來捕獲錯誤
const router = new Router({
// mode: 'history',
routes
});
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);
}
// 當捕獲到加載模塊錯誤時,重新渲染該目標模塊
})
用該方法處理之後,錯誤會依然打印,但是會成功重新渲染模塊