Digital Ninja
Digital Ninja

Reputation: 3731

How to properly handle non-existent named route?

I am using the Vue Router in my project. When i link to a route whose name does not exist, so for example:

<router-link :to="{ name: 'test-route' }"> link </router-link>

Vue complains in the console saying:

[vue-router] Route with name 'test-route' does not exist

But nothing happens to the user to indicate that something is wrong. The address bar gets changed to the root route (just /), but without the homepage actually showing, and my router.onError handler (which usually handles trying to navigate to lazy loaded components when you lose connection) doesn't fire in this case.

I want to show on screen that something is wrong, a redirection to my 404 page if nothing else.

Upvotes: 1

Views: 274

Answers (1)

Michael
Michael

Reputation: 5048

My suggestion - don't allow a link to be clickable if it is not valid, you can make a condition inside the v-on directive.
v-on="{ to: <does link exist (access router)> ? { name: 'test-route' } : null}".
Might need some syntax fixing but that's the general idea.

Upvotes: 1

Related Questions