vue-router 懶加載報錯 Loading chunk {n} failed

懶加載

懶加載:避免單頁面應用一次性加載全部組件造成加載時間過長。
使用:

// 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);
  }
  // 當捕獲到加載模塊錯誤時,重新渲染該目標模塊
})

用該方法處理之後,錯誤會依然打印,但是會成功重新渲染模塊

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章