In this tutorial, you’ll learn how to react to params changes in the same component.
For example, you have a /products/google-glass
route that uses a Product.vue
component. It’s a reusable component, that loads product information from the backend server for a selected product.
Your goal is to make this component react to params changes, e.g. when you open /products/ps4
it should load information about PlayStation 4.
Reacting to params changes in Vue.js
watch: {
'$route' () {
this.loadProduct()
}
}
We can react to params changes by watching the $route
object.
This way we can load product information when the route changes. We simply call a loadProduct()
method whenever the route changes.
The loadProduct()
method will make an API call by sending product slug or id to the backend server:
this.$store.dispatch('LOAD_PRODUCT', { product: this.$route.params.product })
If you find this post useful, please let me know in the comments below.
Cheers,
Renat Galyamov
Want to share this with your friends?
👉renatello.com/watch-params-changes-in-vue-js
PS: Make sure you check other Vue.js tutorials, e.g. Top 5 CSS frameworks for your Vue.js project (2019), Vue.js custom watchers or how to return a promise from Vuex action in Vue.js.