0

I'm learning how to use vue router and I can't understand how to do something.

I have a route with this path: '/entry/:id/'. So, I want a detail page.

I loop through every entry with v-for, obviously, get the id from that entry and then send it as param to router-link, like so:

<router-link :to="{ name: 'entry-detail', params: {id: entry.id} }">

When the link is accessed, I get the this.$route.params.id and I'm able to make a get request to API in order to get that specific entry. The problem is that when I access the entry-detail page with an invalid id that doesn't exist (e.g. /entry/invalid_id/), it gets me the layout without the data, fair enough, but how can I manage to redirect from that page or displaying 404 template instead of just having a blank filled page?

Sorry for my grammar mistakes, by the way.

Thanks in advance for answers!

0

1 Answer 1

2

Assuming your ajax response returns an error code, then you should be able to catch this and handle it in your response, I'm using axios here:

axios.get('/api/results/' + this.$route.params.id).then(response => {
  // success, set the model variables
}).catch(error => {
  // Nope, let's check what the error was
   if(error.response.status === 404){    
     // redirect user   
     this.$router.push('/notFound')
   }
})

If you don't get an error response you can just redirect when data is null:

axios.get('/api/results/' + this.$route.params.id).then(response => {
  // success, set the model variables
  if(response.data == null){
    this.$router.push('/notFound')
  }
  // success, set the model variables
}).catch(error => {
  // Handle errors
})
Sign up to request clarification or add additional context in comments.

1 Comment

I use axios too. Thanks for the answer, I think this solved my problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.