Dynamic Routing — Transcript

Transcript of the free Vue.js lesson Dynamic Routingwatch the video lesson.

Adding routes to your router is usually done via the routes option. However, in some situations, you might want to add or remove routes while the application is already running. In this lesson, let's take a look at a bit of a contrived example. On the home page, let's change our trigger router error button to say add dynamic route.

And we'll also change its click handler to a function by the same name. Down in the Methods section, let's replace the triggerRouterError function with our new click handler. router and pass it a new route record. We can say that we want this route to be named dynamic and exist at the path of slash dynamic.

And as we did previously, just use the login page component as the view. That way we don't have to create any new page components. Cool. Now whenever a user clicks the Add Dynamic Route button, they'll have a new route supported in the application.

Finally, let's add a link to our new page up here by the button. That way, we have a way to test things out. Over in the browser, I'll click the link to the dynamic route. And as you might expect, we get a four or four page because the route doesn't exist yet.

However, if I go back to the homepage, click add dynamic route, and then visit the link again, this time we go to slash dynamic and we see the login form. Very cool. If I give the page a refresh, though, we do get the . So it's worth mentioning that adding dynamic routes based on a user event like this only works for the life of the SPA in the user's browser tab.

Refreshing the SPA or trying to visit this route in a different tab or on another machine will always . The reason is because the route hasn't been added for all those particular application instances. As I mentioned, this is a bit of a contrived example and probably not extremely useful for most real-life applications. Thus, a more realistic use case for adding routes dynamically might be creating a Vue plugin with some out-of-the-box pages that don't rely on a user event to add the routes.

So different use case, but now you'll have the technical know-how to be able to handle it. All right. Just like you can add routes dynamically, you could also remove routes dynamically, and this can actually be done in a few different ways. First calling add route actually produces a callback function to remove that route.

So we could set the return of add route here to a variable, removeDynamicRoute. Then we can call that function whenever we'd like to remove the route. Alternately, we could also override the dynamic route by providing another route with the same name. Lastly, we can also remove routes by their name, like this.

In conclusion, if you ever find yourself in a situation where you can't alter the routes option that's initially passed the router instance, you can still add and remove routes with the add route and remove route functions.