What is a Router Resolver?
In the most simplest of terms, I’d say a Router Resolver allows you to get data before navigating to the new route.
What’s the use case?
One way to deal with getting and displaying data from an API is to route a user to a component, and then in that component’s created hook call a method in a service to get the necessary data. While getting the data, perhaps the component can show a loading indicator.
But, in cases where you want the API data to be fetched before the component is initialised, this strategy fails and this is where Route Resolvers are used.
How to implement?
Vue Router provides beforeEnter hook to take action before a route is resolved, we can use this hook as a point to bind our route resolver.
The resolver function is going to do the API calling stuff to resolve and set data in the destination route’s meta key.
Route’s Meta is an object that contains additional information related to a route. We will utilise this object to store our data.
In the above code, getList is a function that returns Promise<List> and we await for the data to be resolved before we call next() to resume the routing.
Now, in the component we can consume the data by reading it from the route’s meta.
So, this is how we can create and use Route Resolvers in Vue.Js.