When using Vue Router with routes like /foo/:val
you have to add a watcher to react for parameter changes. That results in somewhat annoying duplicate code in all views that have parameters in the URL.
This could look like the following example:
export default { // [...] created() { doSomething.call(this); }, watch: { '$route' () { doSomething.call(this); } }, } function doSomething() { // e.g. request API, assign view properties, ... }
Is there any other way to overcome that? Can the handlers for created
and $route
changes be combined? Can the reuse of the component be disabled so that the watcher would not be necessary at all? I am using Vue 2, but this might be interesting for Vue 1, too.
One possible answer that I just found thanks to a GitHub issue is the following.
It is possible to use the key
attribute that is also used for v-for
to let Vue track changes in the view. For that to work, you have to add the attribute to the router-view
element:
<router-view :key="$route.fullPath"></router-view>
After you add this to the view, you do not need to watch the $route
anymore. Instead, Vue.js will create a completely new instance of the component and also call the created
callback.
However, this is an all-or-nothing solution. It seems to work well on the small application that I am currently developing. But it might have effects on performance in another application. If you really want to disable the reuse of the view for some routes only, you can have a look at setting the key
's value based on the route. But I don't really like that approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With