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?
When you want to watch on state level, it can be done this way:
You can also use mapState in your vue component to direct getting state from store.
In your component:
Where
my_state
is a variable from the store.As mentioned above it is not good idea to watch changes directly in store
But in some very rare cases it may be useful for someone, so i will leave this answer. For others cases, please see @gabriel-robert answer
You can do this through
state.$watch
. Add this in yourcreated
(or where u need this to be executed) method in componentMore details: https://vuex.vuejs.org/en/api.html#vuexstore-instance-methods
This is for all the people that cannot solve their problem with getters and actually really need a watcher, e.g. to talk to non-vue third party stuff (see Vue Watchers on when to use watchers).
Vue component's watchers and computed values both also work on computed values. So it's no different with vuex:
if it's only about combining local and global state, the mapState's doc also provides an example:
The best way to watch store changes is to use
mapGetters
as Gabriel said. But there is a case when you can't do it throughmapGetters
e.g. you want to get something from store using parameter:in that case you can't use
mapGetters
. You may try to do something like this instead:But unfortunately
todoById
will be updated only ifthis.id
is changedIf you want you component update in such case use
this.$store.watch
solution provided by Gong. Or handle your component consciously and updatethis.id
when you need to updatetodoById
.