The post How to Rerender a Vue Route When Path Parameters Change appeared first on Qvault.
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.
How to Fix It
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:
-
to
: the target Route Object being navigated to. -
from
: the current route being navigated away from. -
next
: this function must be called to resolve the hook. The action depends on the arguments provided tonext
:-
next()
: move on to the next hook in the pipeline. If no hooks are left, the navigation is confirmed. -
next(false)
: abort the current navigation. If the browser URL was changed (either manually by the user or via back button), it will be reset to that of thefrom
route. -
next('/')
ornext({ path: '/' })
: redirect to a different location. The current navigation will be aborted and a new one will be started. You can pass any location object tonext
, which allows you to specify options likereplace: true
,name: 'home'
and any option used inrouter-link
‘sto
prop orrouter.push
-
next(error)
: (2.4.0+) if the argument passed tonext
is an instance ofError
, the navigation will be aborted and the error will be passed to callbacks registered viarouter.onError()
.
-
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.
Thanks For Reading
Follow us on Twitter @q_vault if you have any questions or comments
Take game-like coding courses on Qvault Classroom
Subscribeto our Newsletter for more educational articles
The post How to Rerender a Vue Route When Path Parameters Change appeared first on Qvault.
Top comments (0)