在页面上找不到Vue-router重定向(404)

http-status-code-404 Vue.js

GONear

2020-03-11

我试图重定向到使用router.beforeEach全局挂钩找不到的页面上的404.html ,但没有成功(使用VueVue-Router1.0):

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

404.html插入不存在的路由时,这不会重定向到页面,只是给我一个空片段。仅当对some-site.com/*进行硬编码时,它才会重定向到预期的some-site.com/404.html

我敢肯定,这里有一个很明显的事情我可以忽略,但是我无法弄清楚是什么。


请注意,我正在寻找的是重定向到新页面,而不是重定向到另一条路线,可以通过使用router.redirect以下代码段中的轻松实现

router.redirect({
    '*': '404'
})

而在我上router.map,我可能会遇到以下情况:

 router.map({
    '/404': {
        name: '404'
        component: {
            template: '<p>Page Not Found</p>'
        }
    }
})

第674篇《在页面上找不到Vue-router重定向(404)》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
Gil伽罗小宇宙 2020.03.11

@mani的原始答案是您想要的,但是如果您也想以正式的方式阅读它,这里是

参考Vue的官方页面:

https://router.vuejs.org/guide/essentials/history-mode.html#caveat

ㄏ囧囧ㄟ 2020.03.11

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

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";
    }
}

您可以created如上所述钩子上执行此操作,也可以在钩子上执行此操作mounted

请注意:

  1. 我尚未验证以上内容。您需要构建应用的生产版本,并确保发生上述重定向。您无法对此进行测试,vue-cli因为它需要服务器端处理。

  2. 通常,在单页应用程序中,服务器会为所有路由请求发送相同的index.html以及应用程序脚本,尤其是在设置了的情况下<base href="/">/404-page.html除非您的服务器将其视为特殊情况并提供静态页面,否则这将对您失败

让我知道它是否有效!

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android