Reputation: 496
I have a Vuex store feeding many Vue components in a somewhat large web app. I would like to be able to watch Vuex states or getters for logging purposes. However, I want to be able to watch them 'globally', i.e. without relying on any particular Vue component. This rules out tricks like
//aComponent.vue
watch:{ '$store.state.data'(value, oldValue) { /*do something here*/ }}
and
//App.vue
created() {
this.$store.watch((state) => state.watchedState) => {/*do something here*/ })
}
Instead, I am looking for a way to watch my Vuex states or getters directly from the module where the store is defined, so that whenever a state changes, I can call a function passing it as arguments the old state and the new state, so as to write the change into a database (ideally the change itself would be detected automatically, as in Vue's watch(new,old) {...}
.
I suppose I should use Vuex native method store.watch()
for this purpose. But so far I have not be able to invoke it from the store module, as desired.
Any clue? Or did I miss something and what I am trying to do would be just as efficiently done with a different technique?
Upvotes: 1
Views: 1527
Reputation: 14171
For watching mutations you have this options.
You can subscribe
to a store and get notified by mutation after it happens.
store.subscribe( (mutation, state) => { })
You can achieve this in a couple of ways:
use subscribe
on the store you create by hand, most likely in main.js
create a plugin that gets appended to each instance of a store and again subscribe
to it
just use the vuex official plugin for logging
For watching getters you probably need to monkey patch the getters
property by hand.
Then again, if you want to watch what happens with vuex during development you can use vuejs tools
Upvotes: 3