如何使用 vue-router 在 vuejs 中创建 404 组件 [英] How to create a 404 component in vuejs using vue-router
问题描述
我是 vuejs 的新手,我正在使用 vue 进行我的第一个项目.我只是想知道当找不到请求的 url 时,我将如何路由到我的 404.vue
组件.
有什么想法吗?
在路由声明中,我喜欢添加:
<预><代码>[...{路径:'/404',组件:未找到},{路径:'*',重定向:'/404'},...]这意味着如果用户被导航到与任何路由都不匹配的路径,它将被重定向到404"路由,其中将包含未找到"消息.
我将其分成 2 条路由的原因是,在您需要的某些数据无法解析的情况下,您还可以通过编程将用户定向到 404 路由.
例如,如果您正在创建博客,您可能有以下路线:
{ 路径:'/posts/:slug',组件:BlogPost }
这将解决,即使提供的 slug 实际上没有检索任何博客文章.为了解决这个问题,当您的应用程序确定未找到帖子时,请执行
return this.$router.push('/404')
或
return router.push('/404')
如果您不在 Vue 组件的上下文中.
不过要记住的一点是,处理未找到响应的正确方法不仅仅是提供错误页面 - 您应该尝试向浏览器提供实际的 HTTP 404 响应.如果用户已经在单页应用程序中,您就不需要这样做,但如果浏览器点击该示例博客文章作为其初始请求,服务器应该真正返回 404 代码.
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.
Any Idea?
In the routes declaration, I like to add this:
[
...
{ path: '/404', component: NotFound },
{ path: '*', redirect: '/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.
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 }
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')
or
return router.push('/404')
if you are not in the context of a Vue component.
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屋!