Programing

vuex 입력을 편집하기 위해 vuex 개체를 바인딩하는 깨끗한 방법

c10106 2022. 5. 3. 21:32
반응형

vuex 입력을 편집하기 위해 vuex 개체를 바인딩하는 깨끗한 방법

vuex 데이터를 입력에 바인딩할 수 있는 깨끗한 방법이 있는가? "vuex의 데이터로 편집 양식을 하이드레이트하려는 경우, v-modeling하기 전에 로컬 개체에 복제하지 않으면 입력에서 돌연변이 오류가 발생하는 경우.

이는 단순한 {...객체} 스프레드가 중첩된 어레이/개체를 복제하지 않고 중첩된 어레이가 여전히 vuex에 연결되어 있는 깊은 개체에서 특히 더 복잡해진다.

이것이 바로 내가 많은 것을 하고 있다는 것을 발견하는 것이다.

created() {
    const productId = this.$route.params.id
    this.product = _.find(this.$store.state.vendor.products.list, { id: productId })
    this.getProduct(productId).then(response => {
      this.product = { ...response }
      const clonedVariants = []
      this.product.variants.data.forEach(variant => {
        clonedVariants.push({...variant})
      })
      this.product.variants = {}
      this.product.variants.data = clonedVariants;
      this.freshProduct = true
    })
  },

필요한 상태 데이터의 깊은 복제 버전을 반환하는 vuex getter를 사용하는 것을 고려하십시오. 그렇지 않으면 의견에서 언급된 바와 같이 lodash 딥 클론 사용을 고려하십시오. _.cloneDeep또는JSON.parse(JSON.strigify(store.state.object))

복제 상태를 반환하기 위해 vuex getter 사용:

const store = new Vuex.Store({
  state: {
    products: [
      { id: 1, text: '...' },
      { id: 2, text: '...' }
    ]
  },
  getters: {
    products: state => {
      return _.cloneDeep(state.products)
    }
  }
})

다음 구성 요소:

import {mapGetters} from 'vuex';

  export default {
    computed: {
      ...mapGetters(['products'])
    },
    created() {
      const productId = this.$route.params.id
      this.product = _.find(this.products, { id: productId })
    },
}

참조URL: https://stackoverflow.com/questions/62489547/vuex-clean-way-to-bind-vuex-objects-to-edit-inputs

반응형