programing

vuex는 redux와 같이 스토어의 여러 속성을 어떻게 변환합니까?

bestcode 2022. 8. 31. 22:44
반응형

vuex는 redux와 같이 스토어의 여러 속성을 어떻게 변환합니까?

상태 돌연변이에 대한 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
    }
  }
})

하지만 두 가지 변화를 일으킬까 봐 걱정입니다.board그리고.fetching각 자산별로 뷰가 두 번 업데이트됩니다.단순한 예에 불과합니다. 저는 하나의 돌연변이로 변이시키는 것이 더 나은 더 복잡한 특성 돌연변이를 가지고 있습니다.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 };
 }

그럼, 이런 걸 찾으세요?

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>

언급URL : https://stackoverflow.com/questions/47239694/vuex-how-mutate-multiple-properties-in-store-like-in-redux

반응형