How to watch for changes in Vuex ?

When using the Vuex in VueJS, it can be useful to watch for changes in the store. To do so, you can make use of watch method, like so :

1
2
3
4
5
6
this.$store.watch(
      state => state.parameters,
      () => {
        console.log('The parameters have changed!');
      },
);

This will watch the parameters state key. Whenever it changes, the function from line 3 will be executed.

Note that you can also watch other things than directly the state, like getters for example :

1
2
3
4
5
6
this.$store.watch(
      () => this.$store.getters.userData,
      () => {
        console.log('The user data have changed');
      },
);

You can put the watchers in the beforeCreate lifecycle hook for example.

updatedupdated2020-03-292020-03-29