I have the following store.
MyStore.vue
export default {
namespaced:true,
state: {
data: [],
}
// actions, mutations, etc
}
I would like to know when new data arrives in the store.
MyOtherVueFile.vue
export default {
computed: {
getFoo() {
return this.$store.state.MyStore.data;
},
},
watch: {
getFoo(newValue, oldValue) {
console.log(`New ${JSON.stringify(newValue)}`);
console.log(`Old ${JSON.stringify(oldValue)}`);
}
},
}
However the console always shows the new and old data to be the same object. Is this the correct syntax for doing so?
FYI - I need to capture when new items are added to the vuex store data, as I am adding them directly to an OpenLayers Map.
Yes, you can setup watcher on computed property, see the fiddle.
Pinia has a Simpler API than Vuex Pinia's API is simpler and more intuitive than Vuex. Getting started with state management is much easier even for a junior developer as a lot of boilerplate code that needed to be written between every state change in Vuex has now been removed in Pinia.
Both of these could do the work of Vuex, but they aren't enough to replace Vuex completely. Let's take a look at why Vuex is is still necessary, even in Vue 3. First, Vuex offers advanced debugging capabilities that Vue 3 features does not.
I solved it via
this.$store.subscribe((mutation,state) => {
if (mutation.type === 'myStore/MyMutation') {
const myData = mutation.payload.data.forEach(x=> etc...
}
});
You can watch a store property directly like this:
watch:{
'$store.state.data'(value, oldValue) {
}
}
You can also use the 'deep' and 'handler' syntax to watch sub properties on an object.
If you want the old data for an array, you will need to make deep or shallow copy in the watch handler and maintain it in the component.
Unfortunately when working with objects and arrays, you will not be able to see the old state of the object, with the new state, unless the actual object changes (replacing, not mutating).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With