LotTaeza
LotTaeza

Reputation: 87

How can I directly set value in state of VueX

I just want to change data in state of VueX without pass value through following step Action > Mutation > State then getData from state of VueX in other component, Is it possible to do or anyone has another best way to do send value with array to ...mapAction please explain me,

Actually, I just want to send data with array to other component which the data will be change every time when user selected checkbox on Treevue component that I used it.

Thank a lot.

## FilterList.vue ##
export default {
  data() {
    return {
      listSelected: ['aa','bb','cc','...'],  // this value will mutate when user has selected checkbox
    }
  }
}

=================================================================
## store.js ##
export default new Vuex.Store({
  state = {
    dataSelected: [ ]
  },
  mutation = {
    FILTERSELECTED(state, payload) {
      state.selected = payload
    }
  },
  action = {
    hasSelected(context,param) {
      context.commit('FILTERSELECTED',param)
    }
  },
  getters = {
    getSelected: state => state.dataSelected,
  }
  
  strict: true
})

Upvotes: 3

Views: 10506

Answers (1)

Bob Fanger
Bob Fanger

Reputation: 29897

You can set strict: false and change data directly, but I wouldn't recommend it.
You'll lose the benefit Vuex provides, i'd rather share that object outside vuex.

Not every change needs to be synced with the store, it depends on the scenario.
For a EditUser component as example, I'll start with a deep copy of the user object from the store:

this.tmpUser = JSON.parse(JSON.stringify(this.$store.state.user))

This tmpUser is disconnected from the store and won't generate warnings (or updates) when you change its properties.
When the user presses the "save" button, i'll send the changed object back to the store:

this.$store.dispatch("user/save", this.tmpUser)

Which updated the instance in the store and allows the other parts of the application to see the changes.

I also only write actions when async (fetching/saving data) is needed. For the sync operations I only write the mutations and the use the mapMutations helper or call $store.commit("mutation") directly.

Upvotes: 2

Related Questions