programing

Vuex는 객체에 새로운 어레이 속성을 추가하고 사후 대응 방식으로 변환 내부의 객체에 요소를 푸시합니다.

prostudy 2022. 7. 17. 17:45
반응형

Vuex는 객체에 새로운 어레이 속성을 추가하고 사후 대응 방식으로 변환 내부의 객체에 요소를 푸시합니다.

공식 문서에 따르면 vuex 돌연변이는 반응성에 제한이 있습니다.

개체에 새 속성을 추가할 때 수행해야 하는 작업해야 합니다.

Vue.set(obj, 'newProp', 123)

이거 괜찮네요.반응성을 해치지 않고 새로운 어레이 속성을 추가하고 요소를 푸시하려면 어떻게 해야 할까요?

이것이 지금까지 제가 해 온 일입니다.이것은 정상적으로 동작하고 있습니다만, 문제는 반응하지 않는 것입니다. Getters주(州)에 일어나는 변화를 인식할 수 없습니다.

set_add_ons(state, payload) {
        try {

            if (!state.tour_plan[state.tour_plan.length - 1].add_ons) {
                state.tour_plan[state.tour_plan.length - 1].add_ons = [];
            }
            state.tour_plan[state.tour_plan.length - 1].add_ons.push(payload);


        } catch (error) {
            console.log("ERR", error)
        }
    },

이 코드를 반응형 코드로 변환하려면 어떻게 해야 합니까?

사용할 수 있습니다.Vue.set작성하다add_onsAtribute를 reactive로 합니다.어레이에서도 동작합니다.

Vue.set(state.tour_plan[state.tour_plan.length - 1], 'add_ons', []);

데모:

new Vue({
  el: '#app',
  data: {
    items: [{ id: 0 }]
  },
   methods: {
    addArray () {
      if (!this.items[this.items.length-1].add_on)
        this.$set(this.items[this.items.length - 1], 'add_on', [])
      this.items[this.items.length - 1].add_on.push(1)
    }
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <button v-on:click="addArray">
    Add 1 to add_on create if not exists
  </button>
  <div v-for="item in items">add_on content: {{ item.add_on }}</div>
</div>

언급URL : https://stackoverflow.com/questions/53440846/vuex-add-new-array-property-to-an-object-and-push-elements-to-that-object-inside

반응형