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?
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.
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters({
myState: 'getMyState'
})
}
}
In your store:
const getters = {
getMyState: state => state.my_state
}
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