search

Home  >  Q&A  >  body text

Watch in Vuejs/Nuxtjs cannot monitor changes in object arrays from Vuex Store

I am developing an application using Vuejs/Nuxtjs In this application I have a component IdentifiersNode.vue where I want to monitor the Vuex storage array identifiersArray.

I can observe direct changes to identifiersArray such as push, direct key value changes, but when I add new objects to the objects in identifiersArray, watch will cause

P粉063039990P粉063039990332 days ago519

reply all(2)I'll reply

  • P粉846294303

    P粉8462943032024-03-27 12:25:54

    If you use vuex, I recommend using mapGetters to get your items from the store. This will automatically monitor the value and re-render every time the item changes.

    Here is the documentation: Documentation

    Small example

    shop

    import Vue from "vue";
    import Vuex from "vuex";
    
    Vue.use(Vuex);
    
    const state = {
      data: ["Hello", "world"]
    };
    
    const mutations = {
      addItem(state, item) {
        state.data.push(item);
      }
    };
    
    const getters = {
      getData: (state) => state.data
    };
    
    export default new Vuex.Store({
      state,
      mutations,
      actions,
      getters
    })
    

    Component

    
    
    sssccc
    
    

    The following is a codepen as an example: https://codesandbox.io/s/vuex-store-forked-bl9rk0?file=/src/components/HelloWorld.vue

    If you want %E

    reply
    0
  • P粉561323975

    P粉5613239752024-03-27 00:58:34

    Providing an answer may help others in the future.

    I'm actually appending the object to an existing object in an array in the Vuex Store. Therefore, the watch cannot recognize the change. I changed it to vue.set and this worked for me.

    Previously I used append to existing object:

    identifiersNode.instanceData = payload.instanceData

    Later I changed it to:

    // Use the Vue reactive approach to add the instanceData object to existing object
    Vue.set(identifiersNode, 'instanceData', payload.instanceData)

    The following is my Vue component.

    reply
    0
  • Cancelreply