Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Watching a vuex store

Tags:

vue.js

vuex

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.

like image 439
ekjcfn3902039 Avatar asked Feb 25 '19 16:02

ekjcfn3902039


People also ask

Can you watch a computed property Vue?

Yes, you can setup watcher on computed property, see the fiddle.

Is pinia better than Vuex?

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.

Is Vuex necessary in vue3?

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.


2 Answers

I solved it via

this.$store.subscribe((mutation,state) => {
  if (mutation.type === 'myStore/MyMutation') {
    const myData = mutation.payload.data.forEach(x=> etc...
  }
});
like image 155
ekjcfn3902039 Avatar answered Sep 30 '22 02:09

ekjcfn3902039


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).

like image 27
Steven Spungin Avatar answered Sep 30 '22 04:09

Steven Spungin