javascript - Vue编辑已作为prop传递给组件的v-data

标签 javascript vue.js vuejs2 nuxt.js

我正在使用 Nuxt 2.15.3 .
在我的应用程序中,用户可以设置客户可以回答的问题,问题可以是多种类型,其中之一是多项选择题。这些类型的问题有一个标题,以及人们可以选择的多个答案选项。
在我的问题页面上,我列出了所有用户的问题,并且我希望允许他们编辑任何问题,但是我在弄清楚如何准确地做到这一点时遇到了一些麻烦,至少在编辑多项选择题时是这样。就目前而言,我有一个 EditQuestion我向其传递 question 的组件来自我的 QuestionCard 的 Prop 组件,prop 只是存储在 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}.让我困惑的部分是为什么当我修改 questionTitle 时 Vuex 没有提示数据对象,并且仅在编辑 questionOptions?
如果相关,供引用,question.title只是一个简单的字符串,而 question.options是一个看起来像这样的对象:
{
  "0": {
    "id": 0,
    "content": "Option 1"
  },
  "1": {
    "id": 1,
    "content": "Option 2"
  }
}
我允许人们编辑多项选择题选项的最佳方式是什么?

最佳答案

在 JavaScript 中,primitives ( StringNumberBigIntBooleanundefinednull )按值复制,而 objects (包括 ArrayMapWeakMapSetWeakSet )通过引用复制。this.question.titleString ,因此它按值复制到新变量中。另一方面,this.question.options是一个对象(它看起来像 Array ),所以它通过引用复制到 questionOptions ,因此 questionOptionsthis.question.options在 Vuex 中引用同一个对象。
您克隆传入 this.question.options 的想法正在寻找解决方案的正确轨道,但是 Object.assign() spread operator只创建仍然引用相同原始对象的浅拷贝,这解释了当您的组件尝试修改浅拷贝时 Vuex 状态突变警告。
有几个ways to deep-copy an object ,其中之一在 the other answer here 中提供:

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

关于javascript - Vue编辑已作为prop传递给组件的v-data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68852575/

相关文章:

forms - 浏览器返回页面时 Vue.js 表单数据绑定(bind)丢失

vue.js - 当我添加 vue-i18n (karma + mocha + phantomJs) 时,Vue 项目测试失败

javascript - 转换内部的 D3.js 转换

javascript - 将 Controller 之间的数据存储为唯一的

javascript - 无法通过动态导入访问对象属性。 Vue.js + ts

vue.js - 将函数作为属性传递给 Vue 组件

javascript - 如何在多个 Axios 调用上运行回退?

javascript - 为什么不显示在 react ?

javascript - 如何在 jquery 的 .html() 中设置文本样式

javascript - 如何让我的 javascript 动画更快?