We can easily watch for Vuex store changes in a Vue.js app by adding computed properties or using getters.
In this article, we’ll look at how to do watch the Vuex store state with both ways.
We can use computed properties to watch for the latest value from the store and return it. For instance, we can write the following code to create a store and then access the value in a component:
Here is the code for main.js
and App.vue
:
<template><div id="app"><button @click="increment">Increment</button><p>{{count}}</p></div></template><script>export default {name: "App",computed: {count() {return this.$store.state.count;}},methods: {increment() {this.$store.commit("increment");}}};</script>
In the code above, we have the store in main.js
, which holds the count state.
We put the store
in our Vue
instance. In App.vue
, we reference the store by using this.$store
.
Then, we can access the count
state we did in the count
method in the computed
property.
In the end, we see the latest count
displayed on the screen as we click the Increment button to call increment
, which commits a new value to the store.
We can create a getter in the store and then use the mapGetters
method to add the getter as a computed property in our component. For instance, we can write the following to do that:
<template><div id="app"><button @click="increment">Increment</button><p>{{count}}</p></div></template><script>import { mapGetters } from "vuex";export default {name: "App",computed: {...mapGetters(["count"])},methods: {increment() {this.$store.commit("increment");}}};</script>
In the code above, we added a getter in our store
with,
getters: {
count: state => {
return state.count;
}
}
in main.js
. Then, in the script
section of App.vue
, we have,
import { mapGetters } from "vuex";
export default {
name: "App",
computed: {
...mapGetters(["count"])
},
methods: {
increment() {
this.$store.commit("increment");
}
}
};
We have imported the mapGetters
method from vuex
to add the getter directly as a computed property.
In the array we passed into mapGetters
we pass in the getter name from the store to access the returned value from the getter.
Therefore, we’ll see the same result as before.
Computed properties are good for getting some simple states. If we need to derive states from a given state, then we should use getters with the mapGetters
method to map them to computed properties.