且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

找不到页面上的 Vue 路由器重定向 (404)

更新时间:2023-11-27 08:49:28

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

I think you should be able to use a default route handler and redirect from there to a page outside the app, as detailed below:

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 组件定义中,您可以指定实际的重定向,这将使您完全退出应用程序:

In the above PageNotFound component definition, you can specify the actual redirect, that will take you out of the app entirely:

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

您可以在 created 钩子上执行,如上所示,也可以在 mounted 钩子上执行.

You may do it either on created hook as shown above, or mounted hook also.

请注意:

  1. 我没有验证以上内容.您需要构建应用程序的生产版本,确保上述重定向发生.您不能在 vue-cli 中对此进行测试,因为它需要服务器端处理.

  1. I have not verified the above. You need to build a production version of app, ensure that the above redirect happens. You cannot test this in vue-cli as it requires server side handling.

通常在单页应用程序中,服务器发送相同的 index.html 以及所有路由请求的应用程序脚本,特别是如果您设置了 代码>.这对于您的 /404-page.html 将失败,除非您的服务器将其视为特殊情况并为静态页面提供服务.

Usually in single page apps, server sends out the same index.html along with app scripts for all route requests, especially if you have set <base href="/">. This will fail for your /404-page.html unless your server treats it as a special case and serves the static page.

让我知道它是否有效!

Vue 3 以后的更新:

如果您使用 Vue 3 作为旧版本,则需要将 '*' 路径属性替换为 '/:pathMatch(.*)*'不再支持 '*' 的全部路径.路线看起来像这样:

You'll need to replace the '*' path property with '/:pathMatch(.*)*' if you're using Vue 3 as the old catch-all path of '*' is no longer supported. The route would then look something like this:

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

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

See the docs for more info on this update.