vuex 如何像在 redux 中一样改变 store 中的多个属性?

luz*_*zny 5 vue.js react-redux vuex vuejs2

Vuex 状态突变方法如下:

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
    }
  }
})
Run Code Online (Sandbox Code Playgroud)

但我担心它会触发两个转变boardfetching独立,而不是一个,我的观点将被更新双重时间为每个属性。这只是一个简单的例子,我有更复杂的属性突变,可以更好地通过一个突变进行突变。在 vuex 中可以吗?

我喜欢 redux 方法来返回只变异一次的状态对象:

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 };
 }
Run Code Online (Sandbox Code Playgroud)

小智 5

所以,你在寻找这样的东西吗?

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)
  }
})
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)