如何使用vue-router在vuejs中创建404组件 [英] how to create a 404 component in vuejs using vue-router

查看:239
本文介绍了如何使用vue-router在vuejs中创建404组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是vuejs的新手,并且正在使用vue进行我的第一个项目.我只是想知道当找不到所请求的URL时如何路由到404.vue组件.

I'm new to vuejs and I'm working on my first project with vue. I'm just wondering how I will route to my 404.vue component when the requested url is not found.

有什么想法吗?

推荐答案

在路由声明中,我想添加以下内容:

In the routes declaration, I like to add this:

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

这将暗示如果用户导航到与任何路由都不匹配的路径,它将被重定向到"404"路由,其中​​将包含未找到"消息.

Which will imply that if the user is navigated to a path which does not match any routes, it will be redirected to the "404" route, which will contain the "not found" message.

我将其分为2条路由的原因是,这样,当您需要的某些数据无法解析时,您也可以以编程方式将用户定向到404路由.

The reason I've separated it into 2 routes is so that you can also programmatically direct the user to the 404 route in such a case when some data you need does not resolve.

例如,如果您正在创建博客,则可能具有以下路线:

For instance, if you were creating a blog, you might have this route:

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

即使提供的slug实际上未检索任何博客文章,也可以解决.要解决此问题,当您的应用程序确定未找到帖子时,请执行

Which will resolve, even if the provided slug does not actually retrieve any blog post. To handle this, when your application determines that a post was not found, do

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

return router.push('/404')

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

if you are not in the context of a Vue component.

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

One thing to bear in mind though is that the correct way to handle a not found response isn't just to serve an error page - you should try to serve an actual HTTP 404 response to the browser. You won't need to do this if the user is already inside a single-page-application, but if the browser hits that example blog post as its initial request, the server should really return a 404 code.

这篇关于如何使用vue-router在vuejs中创建404组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆