supernova
supernova

Reputation: 127

Vue redirect back to '/' if 404 not found

I have a Vue application with the following routes:

export default new Router({
    mode: 'history',
    routes: [
        {
            path: '/',
            name: 'input',
            component: Input
        },
        {
            path: '/result/:city',
            name: 'result',
            component: Result
        }
    ]
})

I know that if I do a new path with path: '*' and component: someErrorPage, I can show an error page. However, I'd like to redirect back to the input path so they can try again.

EDIT:

After doing some research and looking at my app, I found that if I search an invalid query, it will take me to corresponding route anyway, but not show me the data. Example: If I search a valid city (eg. New York), I am redirected to localhost:8080/result/New York with the correct data. However, if I do an in valid query (eg. a;fldkalf), I will be taken to localhost:8080/result/a;fldkalf without any data. This means that path: '*' will not help me here.

EDIT 2: I think I may have found something that will help, but I am not sure how to execute it. Vue has something called navigation guards (https://router.vuejs.org/guide/advanced/navigation-guards.html#global-before-guards). If someone could help me make sense of it, that'd be great.

Upvotes: 0

Views: 234

Answers (1)

Adam Orłowski
Adam Orłowski

Reputation: 4484

You can add redirect for * (not found) route:

{
  path: '*', // make sure this is the last route in Array
  redirect: { name: 'input' },
}

Upvotes: 1

Related Questions