我正在使用 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 ( String
、 Number
、 BigInt
、 Boolean
、 undefined
和 null
)按值复制,而 objects (包括 Array
、 Map
、 WeakMap
、 Set
、 WeakSet
)通过引用复制。this.question.title
是 String
,因此它按值复制到新变量中。另一方面,this.question.options
是一个对象(它看起来像 Array
),所以它通过引用复制到 questionOptions
,因此 questionOptions
和 this.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/