In single-page apps that use the Vue Router, it is common to create a path parameter that changes the behavior of a route. A common problem occurs when a user alters the path manually in the address bar. Manually changing the URL does not rerender the view! This can cause unexpected behavior because mounted() hooks don't fire and nested components don't reload.
The solution is to use another hook, beforeRouteUpdate(). Let's take the example of the Qvault Playground. The last parameter in the Playground's path is the code language, "js" or "go". If the boilerplate code were only fetched using a mounted() hook, then when a user changed the path parameter the boilerplate code wouldn't reload.
The reason that it does reload is that the Qvault SPA also has the following beforeRouteUpdate() hook:
beforeRouteUpdate (to, from, next) {
this.lang = to.params.lang;
this.setCode();
next();
}
According to the docs, the hook receives three parameters:
1. to: the target Route Object being navigated to.
2. from: the current route being navigated away from.
3. next: this function must be called to resolve the hook. The action depends on the arguments provided to next:
In the case of the Qvault Playground, we are just doing the same operation that the mounted() hook does: we check the language and fetch the boiler plate.
If this is a common problem in your app, you can set your entire router-view to re-render when its path changes by providing a key property:
<router-view :key="$route.fullPath" />
With the above, you won't need to use the beforeRouteUpdate() hook, and can directly access the now-reactive this.$route.params.myVar property. The only problem with this method is that every path in that router will update in the case of a path change. You may not want all that needless re-rendering, but that's a decision for you to make.
Follow us on Twitter @q_vault if you have any questions or comments
Take game-like coding courses on Qvault Classroom
Subscribe to our Newsletter for more educational articles
Previously published at https://qvault.io/2020/07/07/how-to-rerender-a-vue-route-when-path-parameters-change/