跳到主内容

Vue-router匹配不到路由时,自动跳转到404页面

· 2分钟阅读

尝试使用 beforeEach 来跳转到 404 页面,但是无效

router.beforeEach(function (transition) {
if (transition.to.path === "/*") {
window.location.href = "/404.html";
} else {
transition.next();
}
});

解决方法

我认为您应该能够使用默认路由处理程序并从那里重定向到应用程序外部的页面,详情如下

const ROUTER_INSTANCE = new VueRouter({
mode: "history",
routes: [
{ path: "/", component: HomeComponent },
// ... other routes ...
// and finally the default route, when none of the above matches:
{ path: "*", component: PageNotFound },
],
});

在上面的 PageNotFound 组件定义中,您可以指定要跳转的页面,例如

Vue.component("page-not-found", {
template: "",
created: function() {
// Redirect outside the app using plain old javascript
window.location.href = "/my-new-404-page.html";
}
}

Vue3 以后的更新

{ path: '/:pathMatch(.*)*', component: PathNotFound },

有关此更新的更多信息,请参阅文档