Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

vue.js - how to create a 404 component in vuejs using vue-router

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...