vuex how mutate multiple properties in store like in redux?

Viewed 3432

Vuex approach for state mutations is as following:

const store = new Vuex.Store({
  state: {
    fetching: false,
    board: null
  },
  mutations: {
    setFething (state) {
      state.fetching = true
    },
    setCurrentBoard (state, board) {
       state.board = board
       state.fetching = false
    }
  }
})

But I’m afraid that it will trigger two changes for board and fetching independently instead one and my view will be updated double times for each property. It is only simple example, I’ve more complex properties mutations that will be better to mutate by one mutation. Is it possible in vuex?

I liked redux approach to return state object mutated only once:

initialState = { board: null, fetching: false };
export default function reducer(state = initialState, action = {}) {
  switch (action.type) {
    case Constants.SET_FETCHING:
      return { ...state, fetching: true };

    case Constants.SET_CURRENT_BOARD:
      return { ...state, ...action.board, fetching: false };
 }
1 Answers

So, are you looking for something like this?

var store = new Vuex.Store({
  state: {
    id: 1,
    name: 'aaa',
    last: 'bbb'
  },
  mutations: {
    change (state, payload) {
      state = Object.assign(state, payload)
    }
  }
})

new Vue({
  el: '#app',
  store,
  created () {
    setTimeout(_ => {
      this.$store.commit('change', {
        id: 2,
        last: 'ccc'
      })
    }, 2000)
    setTimeout(_ => {
      this.$store.commit('change', {
        name: 'ddd'
      })
    }, 4000)
  }
})
<div id="app">
  {{ $store.state.id }}
  <br>
  {{ $store.state.name }}
  <br>
  {{ $store.state.last }}
</div>

<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vuex"></script>

Related