I am using vuex
and vuejs 2
together.
I am new to vuex
, I want to watch a store
variable change.
I want to add the watch
function in my vue component
This is what I have so far:
import Vue from 'vue';
import {
MY_STATE,
} from './../../mutation-types';
export default {
[MY_STATE](state, token) {
state.my_state = token;
},
};
I want to know if there are any changes in the my_state
How do I watch store.my_state
in my vuejs component?
I think the asker wants to use watch with Vuex.
You should not use component's watchers to listen to state change. I recommend you to use getters functions and then map them inside your component.
In your store:
You should be able to listen to any changes made to your store by using
this.myState
in your component.https://vuex.vuejs.org/en/getters.html#the-mapgetters-helper
You can use a combination of Vuex actions, getters, computed properties and watchers to listen to changes on a Vuex state value.
HTML Code:
JavaScript Code:
See JSFiddle demo.
You could also subscribe to the store mutations:
https://vuex.vuejs.org/api/#subscribe
Let's say, for example, that you have a basket of fruits, and each time you add or remove a fruit from the basket, you want to (1) display info about fruit count, but you also (2) want to be notified of the count of the fruits in some fancy fashion...
fruit-count-component.vue
Please note, that the name of the function in the
watch
object, must match the name of the function in thecomputed
object. In the example above the name iscount
.New and old values of a watched property will be passed into watch callback (the count function) as parameters.
The basket store could look like this:
fruit-basket.js
You can read more in the following resources:
Create a Local state of your store variable by watching and setting on value changes. Such that the local variable changes for form-input v-model does not directly mutate the store variable.