【问题标题】:vuex how mutate multiple properties in store like in redux?vuex如何像redux一样改变存储中的多个属性?
【发布时间】:2018-04-24 16:20:47
【问题描述】:

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
    }
  }
})

但我担心它会独立触发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 };
 }

【问题讨论】:

  • 使用 Vuex acrions。创建同时提交多个更改的操作。
  • 情况是我不能一次返回新的不可变状态对象,但我必须分别改变每个属性。

标签: vue.js vuejs2 react-redux vuex


【解决方案1】:

那么,你在寻找这样的东西吗?

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>

【讨论】:

    猜你喜欢
    • 2020-09-26
    • 2014-10-15
    • 2020-10-18
    • 2020-12-01
    • 2019-07-24
    • 2022-01-24
    • 2021-08-14
    • 2019-07-03
    • 1970-01-01
    相关资源
    最近更新 更多