Programing

구성 요소로 전달된 v-data를 소품으로 편집하는 Vue

c10106 2022. 3. 6. 10:50
반응형

구성 요소로 전달된 v-data를 소품으로 편집하는 Vue

나는 Nuxt를 사용하고 있다.2.15.3.

내 앱에서 사용자는 고객이 대답할 수 있는 질문을 설정할 수 있으며, 그 중 하나가 '다중 선택' 질문일 수 있다.이러한 유형의 질문들은 제목과 함께 사람들이 선택할 수 있는 여러 가지 대답 선택사항이 있다.

내 질문 페이지에 사용자의 모든 질문을 나열하고, 어떤 질문이든 편집할 수 있도록 허용하고 싶지만, 적어도 객관식 질문 편집에 관해서는 정확히 어떻게 해야 하는지를 알아내는 데 어려움을 겪고 있다.현재 상태로는, 나는.EditQuestion내가 합격시킨 부품.question내 것을 받쳐 주다.QuestionCard구성 요소, Vuex에 저장된 질문의 세부 정보일 뿐이다.

현재 버전의 (SO에 대해 단순화된)EditQuestion구성 요소:

<template>
  <input v-model="questionTitle" type="text">
  <div v-if="question.type === 'multiple_choice'">
    <input v-for="option in questionOptions" v-model="option.content" type="text">
  </div>
  <button @click.prevent="updateQuestion"></button>
</template>

<script>
  export default {
    props: {
      question: {}
    },
    data() {
      return {
        questionTitle: this.question.title,
        questionOptions: this.question.options
      }
    },
    methods: {
      updateQuestion() {
        // Call the API with the new question details
      }
    }
  }
</script>

만약 내가 질문 제목만 편집했다면, 이건 정말 잘된 일이야.하지만, 내 문제는 옵션에서 나온다.내가 하나를 업데이트하려고 하면, Vuex는 돌연변이를 벗어나 상점 상태를 변이시키는 것에 대해 경고하고, 그것은 내가 복제해도 나에게 똑같이 경고해 준다.question.options예를 들어, 을 함으로써questionOptions: Object.assign({}, this.question.options)또는questionOptions: {...this.question.options}.나를 혼란스럽게 하는 부분은 내가 수정했을 때 Vuex가 불평하지 않는 이유야.questionTitle데이터 개체, 그리고 질문을 편집할 때만 옵션?

참고용으로 만약 관련이 있다면question.title반면에 단순한 끈일 뿐이다.question.options이렇게 생긴 물체야

{
  "0": {
    "id": 0,
    "content": "Option 1"
  },
  "1": {
    "id": 1,
    "content": "Option 2"
  }
}

사람들이 객관식 질문 옵션을 편집할 수 있도록 허용하는 가장 좋은 방법은?

JavaScript에서 원시 요소(String,Number,BigInt,Boolean,undefined그리고null)은 값별로 복사되는 반면, 객체(포함)는Array,Map,WeakMap,Set,WeakSet참조로 복사한다.

this.question.titlea이다String값을 통해 새로운 변수에 복사된다.다른 한편으로는this.question.options하나의 물체(그것은 마치 하나의 물체처럼 보인다)Array() 참조로 복사하여questionOptions, 그리고 따라서questionOptions그리고this.question.optionsVuex에서 동일한 객체를 참조한다.

복제에 대한 당신의 아이디어는this.question.options해결책에 대한 올바른 경로에 있지만, 스프레드 운영자는 여전히 동일한 원래 개체를 참조하는 얕은 복사본만 생성하며, 이는 구성 요소가 얕은 복사본을 수정하려고 할 때 Vuex 상태 유지 경고를 설명한다.

객체를 심층 복사하는 방법에는 여러 가지가 있으며, 그 중 하나는 여기의 다른 답변에서 제공된다.

export default {
  data() {
    return {
      questionTitle: this.question.title,
      questionOptions: JSON.parse(JSON.stringify(this.question.options))
    }
  }
}

데모를 하다

의 로컬 사본을 만들어 보십시오.question해당 로컬 복사본에 대한 모든 업데이트만 수행하고 다음과 같은 작업을 수행하십시오.

<script>
  export default {
    props: {
      question: {}
    },
    data() {
      return {
        localCopyOfQuestion: JSON.parse(JSON.stringify(this.question)),
        questionTitle: this.localCopyOfQuestion.title,
        questionOptions: this.localCopyOfquestion.options
      }
    },
    methods: {
      updateQuestion() {
        // Call the API with the new question details
      }
    }
  }
</script>

참조URL: https://stackoverflow.com/questions/68852575/vue-editing-v-data-that-has-been-passed-to-a-component-as-a-prop

반응형