我正试图重定向到404.使用router.beforeEach全局钩子找不到页面上的html,但没有多大成功(使用Vue1和Vue-Router 1.0):

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

当插入不存在的路由时,这不是重定向到第404.html页,只是给我一个空片段.只有当硬编码一些网站.com/*将重定向到预期的某个站点.com/404.html

我肯定我忽略了一些非常明显的东西,但我不知道是什么.


请注意,我要找的是redirect to a new page, not a redirect to another route,这可以通过使用router.redirect轻松实现,比如以下代码片段:

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

而在我router.map岁的时候,我可以有以下几点:

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

推荐答案

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

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

让我知道它是否有效!

Update for Vue 3 onward:

如果使用Vue 3,则需要将'*'路径属性替换为'/:pathMatch(.*)*',因为旧的'*'路径不再受支持.然后,路由将如下所示:

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

有关此更新的更多信息,请参阅the docs.

Vue.js相关问答推荐

如何禁用Vuetify v—stepper操作按钮

用于循环数组的模板元素内的条件渲染

Vue composition api: 访问