简体   繁体   中英

Vuex getter reactivity issue (in combination with Vue router)

I have a Vuex getter that is supposed to get all relevant data for the current route & then display it in Vuetify <v-data-table> which works completely fine when the component is created. However, when i create a new entry in the data Array in the relevant state that the getter works with, it only fetches & displays the new entry when i navigate away from the current route. I'm using the current route as a key to identify the different entries in the state so i can display different information for the current route, hence the Vue router . I'm not sure if explained my issue clearly (sorry, English is not my first language), so here's code that i think is relevant: The getter in question:

  computed: {
    ...mapGetters({
      geData: "geData"
    }),
    getAllData() {
      return this.geData[this.$route.path];
    }
  }

The data table:

<v-data-table :headers="headers" :items="getAllData" hide-actions>
  <template v-slot:items="props">
        <td class="text-xs-left">{{ props.item.name }}</td>
        <td class="text-xs-left">{{ props.item.state}}</td>
        <td class="text-xs-left">{{ props.item.created_at }}</td>
        <td class="text-xs-left">{{ }}</td>
      </template>
</v-data-table>

Here's how i modify the array in the store mutation :

  setNewData: (state, Data) => {
    state.Data[Data[0]] = Data[1];
  }

The first Data[0] is the route to be used as a key, the second Data[1] is the new data. I suspect the reason the getter updates only when i navigate away from the current route is because i use the route as a key, but i'm not certain and i dont know if that's the case how to adress the issue, so any ideas, pointers are welcome, thanks in advance!

You'll need to use Vue.set because object keys are not reactive unless first declared:

Vue.set(state.Data, Data[0], Data[1])

That should get you the reactivity you're looking for.

Side note:

Make sure that state.Data is reactive to begin with by initializing it as an object.

Try this:

setNewData: (state, Data) => {
  Vue.set(state.Data, Data[0], Data[1])
}

You'll need to import Vue if you don't already have it in that file.

See https://v2.vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats .

I'm assuming here that you're adding a new property to the object. If the property already exists then you wouldn't need Vue.set .

An alternative would be to copy the object, adding the new property before the new object is made reactive:

setNewData: (state, Data) => {
  state.Data = {
    ...state.Data,
    [Data[0]]: Data[1]
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM