【发布时间】:2021-08-15 09:58:44
【问题描述】:
在我的 Vue/Nuxt 项目中,我有一个表单,用户可以在其中添加更新动态字段以用于报价计算。
当表单加载时,将创建一个具有 beforeMount 生命周期的字段,然后用户可以选择创建一个或多个额外的字段。
在我的数据返回中我有这个:
data() {
return {
calculationFields: { qty: 0, price: 3.86, selected: false },
}
}
当用户点击“添加字段”按钮时,会调用 addField 方法:
addField() {
this.$store.dispatch('quantity/updateAdd', this.calculationFields)
},
updateAdd 操作调用 UPDATE_ADD_ITEM 突变的地方
UPDATE_ADD_ITEM(state, value) {
state.options.push(value)
},
value 是{ qty: 0, price: 3.86, selected: false }
这很好用,因为选项数组是用新的字段对象更新的
在模板中,我循环这个数组以输出 X 个字段
<div v-for="(field, index) in getCalculationFields()" :key="field" class="flex-xs justify-between calculation-field">
<InputCustomPlaceholder type="number" :is-required="true" :input-id="`calculation-${index}`" :input-name="`calculation-${index}`" label-text="" placeholder-text="Add pieces" custom-placeholder-text="pcs" extraclass="flex-1 no-margin" />
<a href="#" class="remove-field" @click.prevent="removeField(index)">×</a>
</div>
我现在的问题是,我不知道如何在每个动态创建的输入字段上使用 v-model,以便我可以在选项状态下更新字段对象中的 qty 值。
因此,如果列表包含三个字段,例如:
[
{ qty: 0, price: 3.86, selected: false },
{ qty: 0, price: 3.86, selected: false },
{ qty: 0, price: 3.86, selected: false }
]
因此,当在字段号 2 中使用输入 200 作为数量时,数组将如下所示:
[
{ qty: 0, price: 3.86, selected: false },
{ qty: 200, price: 3.86, selected: false },
{ qty: 0, price: 3.86, selected: false }
]
我相信我必须使用类似的东西
<InputCustomPlaceholder type="number" :is-required="true" :input-id="`calculation-${index}`" v-model="updateOptionList" :input-name="`calculation-${index}`" label-text="" placeholder-text="Add pieces" custom-placeholder-text="pcs" extraclass="flex-1 no-margin" />
但是什么是最好的找到字段的索引并更新数组上该索引中的值。
在非动态输入中,我使用如下内容:
v-model="updateFieldOne"
updateFieldOne: {
set(value) {
this.$store.dispatch('fields/updatePartDimeWidth', value)
}
}
按预期工作。
【问题讨论】:
标签: javascript arrays vue.js nuxt.js vuex