programing

Nuxt / Vue - 돌연변이 처리기 외부에서 vuex 저장소 상태 변경 안 함

prostudy 2022. 5. 21. 08:52
반응형

Nuxt / Vue - 돌연변이 처리기 외부에서 vuex 저장소 상태 변경 안 함

나는 간단한 카트 스토어를 가지고 있어, 아이템을 추가/제거할 수 있다.

카트에 제품을 추가하면 수량을 업데이트할 수 있는 플래시 메시지를 표시한다.내 플래시 메시지 컴포넌트에 어떤 제품이 관련되는지 모르기 때문에 나는 매장을 이용한다.

나는 간단한 부트스트랩 스피너를 가지고 있다.

    <b-form-spinbutton
      :value="value"
      min="1"
      max="26"
      @change="setItems"
    />

이것을 바꾸면, 나는 전화하고 싶다.setItems마지막으로 추가된 항목을 업데이트하기 위한 내 스토어 기능.

그래서 나는 다음을 사용했다.

  data () {
    return {
      value: 1
    }
  },
  methods: {
    setItems (value) {
      const items = [...this.$store.getters['cart/items']]
      // update quantity of the last item - we suppose it's the current item
      items.slice(-1)[0].quantity = value
      this.$store.commit('cart/setItems', items)
    }
  }

여기서 이 오류에 대해 읽었음: Vuex - 돌연변이 처리기 외부에서 Vuex 저장 상태를 변경하지 않음으로 변경v-modelvalue다가오다

나의 가게cart.js:

export const state = () => ({
  items: []
})

export const mutations = {
  setItems (state, items) {
    state.items = items
  },
  // ....

이 문제를 어떻게 처리해야 할지 모르겠어?

스토어 상태가 변이 처리기 외부에서 변이되는 경우 다음과 같은 경우:

items.slice(-1)[0].quantity = value

스프레드 연산자를 사용하여 스토어 항목의 얕은 복사본을 만드십시오.각 항목 속성은 여전히 vuex 상태를 참조한다.다음을 사용하여 상세 복사본을 만들 수 있음:

const items = JSON.parse(JSON.stringify(this.$store.getters['cart/items']))

또는, 프로젝트를 진행 중인 경우:

const items = _.cloneDeep(this.$store.getters['cart/items'])

참조URL: https://stackoverflow.com/questions/68047905/nuxt-vue-do-not-mutate-vuex-store-state-outside-mutation-handlers

반응형