小知识,大挑战!本文正在参与“程序员必备小知识”创作活动
vue项目新增了页面google浏览器访问是没有问题,但是页面嵌入webview中,破平板性能不行,加载不到页面,能访问到main.js,后来发现是路由跳转失败。查资料发现 vue router 设置为异步加载,会出现此问题 :
[vue-router] Failed to resolve async component default: ChunkLoadError: Loading chunk about failed.
github.com/vuejs/vue-r…
总结了两中方案,一中修改router error处理逻辑,另一种将页面改为正常加载
方案一:
路由组件还是为异步加载,处理router.error
import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter);
const routes = [
{
path: "/appLoginRedirect",
name: "AppLoginRedirect",
component: () =>
import(
/* webpackChunkName: "about" */ "../views/login/AppLoginRedirect/index.vue"
),
// meta: { requiresAuth: true },
},
];
const router = new VueRouter({
mode: "history",
base: process.env.BASE_URL,
routes,
});
在路由拦截出添加 router.onError()
router.onError((error) => {
// 路由异步加载出现error:ChunkLoadError: Loading chunk about failed, 重新加载一次页面
const pattern = /Loading chunk about failed/g;
const isChunkLoadFailed = error.message.match(pattern);
const targetPath = router.history.pending.fullPath;
if (isChunkLoadFailed) {
router.replace(targetPath);
}
})
方法二
路由组件改为正常加载
import Vue from "vue";
import VueRouter from "vue-router";
import AppLoginRedirect from "../views/login/AppLoginRedirect/index.vue";
Vue.use(VueRouter);
const routes = [
{
path: "/appLoginRedirect",
name: "AppLoginRedirect",
component:AppLoginRedirect
// meta: { requiresAuth: true },
},
];
const router = new VueRouter({
mode: "history",
base: process.env.BASE_URL,
routes,
});
咱是容不得开发调试工具爆红的,顺带手说说router其他错误。
第一种错误:
Error: Redirected when going from “/a“ to “/b“ via a navigation guard.
第二种错误:
Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location: "/a".
幸运的是这两中错误都用同一种解决方法: 在router配置文件中增加 下面一段话
import VueRouter from "vue-router";
// Error: Redirected when going from “/a“ to “/b“ via a navigation guard.
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
return originalPush.call(this, location).catch(err => err)
}
Vue.use(VueRouter);