Problem statement could be:
- How to watch mutations in VueJS [vue 2]
- How to know if a mutation is commited?
- How to know if a state data has been changed?
Hello folks, so there is one simple way to know if any mutation has been committed across the Vue component. and that is $store.subscribe
` function. Like with help of this you can subscribe mutations and after that, you can filter this out using mutation type[usually the name of mutation]
So, let’s suppose, In component 1, I’m firing a mutation called INCREMENT_NUMBER
on @click. Which will increase our count data in state by 1.
But I want to know if this mutation gets committed inside component 2. So, here all I need to do is just define subscribe function inside mounted or created hook. And this will watch our mutation.
mounted(){
this.$store.subscribe(mutation => {
if(mutation.type == 'INCREMENT_NUMBER'){
console.log('You got an increment by 1')
}
});
}
Now what will happen, It will record all of your mutations and you will be able to filter them out by their name as I did above. You can also use this method or trick to watch if state data gets changed.
Thanks for visiting 🙂 Don’t forget to upvote or downvote, and if you have found anything better than this then do let me know in the comment section.