如何使用vue-router在vuejs中创建一个404组件

How to create a 404 component in vuejs using vue-router

我是 vuejs 的新手,我正在使用 vue 开发我的第一个项目。我只是想知道当找不到请求的 url 时我将如何路由到我的 404.vue 组件。

有什么想法吗?

我所做的是将 http-found 的 class 提供给父级 div 我所有的组件和 App.vue 的安装挂钩我检查使用jQuery 或 Javascript 如果有任何元素带有 http-found 的 class 如果没有我重定向到我的 404 页面。

App.vue

mounted(){
   if(!$('.http-found')){
     this.$router.push('/404')
   }
}

有几种方法可以做到这一点。

最通用的方法是在导航前检查路径是否与任何路线匹配,如果不匹配则重定向到 未找到 页面。

router.beforeEach((to, from, next) => {
  if (!to.matched.length) {
    next('/notFound');
  } else {
    next();
  }
});

参见JSFiddle

在路由声明中,我想添加:

[
  ...  
  { path: '/404', component: NotFound },  
  { path: '*', redirect: '/404' },  
  ...  
]

这意味着如果用户被导航到一个不匹配任何路由的路径,它将被重定向到“404”路由,其中​​将包含 "not found" 消息。

我将其分成 2 条路线的原因是,在您需要的某些数据无法解析的情况下,您还可以通过编程将用户定向到 404 路线。

例如,如果您正在创建一个博客,您可能有这样的路线:

{ path: '/posts/:slug', component: BlogPost }

这将解决,即使提供的 slug 实际上没有检索到任何博客 post。要处理此问题,当您的应用程序确定未找到 post 时,请执行

return this.$router.push('/404')

return router.push('/404')

如果您不在 Vue 组件的上下文中。

但要记住的一件事是,处理未找到响应的正确方法不仅仅是提供错误页面 - 您应该尝试向浏览器提供实际的 HTTP 404 响应。如果用户已经在单页应用程序中,则不需要执行此操作,但如果浏览器将示例博客 post 作为其初始请求,服务器实际上应该 return 404代码。

@g-wilson 回答后我去了 { path: '*', component: NotFound }。如果您不想进行重定向,可能会有用。

现在在 Vue 3 中 path: '*' 将不起作用。我们必须使用正则表达式:/:catchAll(.*)

我们可以直接使用而不是使用path: "*"

{
    // path: "*",
    path: "/:catchAll(.*)",
    name: "NotFound",
    component: NotFound,
}

{
    path: '/404', name: 'NotFound', component: NotFound
},
{
    path: '/:catchAll(.*)', redirect:'404'
}

我从

那里得到的