yierstem
yierstem

Reputation: 2067

Vue Router with invalid parameter

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!

Upvotes: 0

Views: 2739

Answers (1)

craig_h
craig_h

Reputation: 32734

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
})

Upvotes: 2

Related Questions