Vue中v-for结合v-model动态生成数组对象的问题
解决v-for生成输入框时数组对象存储异常的问题
你遇到的问题核心是数组和对象的使用逻辑混淆了,咱们一步步理清楚:
为什么你的代码会得到奇怪的结果?
你把newEntries初始化成了空数组,但却用newEntries[fund.id]['id']这种对象键值的方式去赋值。数组的索引是连续的数字序列,当你用fund.id(比如1、2)作为索引时,数组会自动填充前面未定义的索引位为null;而且你直接给newEntries[fund.id]['amount']赋值时,其实是把数组的第fund.id个位置直接设成了字符串,而不是对象里的amount属性,所以才会得到[null, '50.00', '123.45']这种不符合预期的结构。
两种可行的解决方案
方案一:先存为对象,再转成目标数组
这种方式适合fund.id不是连续数字的场景:
- 初始化数据:把
newEntries改成对象类型data() { return { defaultFunds: [...], // 你的原始基金数据 newEntries: {} } } - 预先创建对应对象:在组件创建时,给每个
fund.id初始化对应的对象(避免Vue响应式问题)created() { this.defaultFunds.forEach(fund => { this.$set(this.newEntries, fund.id, { id: fund.id, amount: '' }) }) } - 调整模板绑定:
<table class="table m-0"> <tbody> <tr v-for="fund in defaultFunds" :key="fund.id"> <td> {{fund.name}} <b-input v-model="newEntries[fund.id].id" :value="fund.id" name="entryFund" type="text" class="d-none" /> </td> <td> <b-input v-model="newEntries[fund.id].amount" name="newFundAmount" type="text" placeholder="Amount" /> </td> </tr> </tbody> </table> - 获取目标数组:当需要提交或使用数据时,把对象转成数组
const finalEntries = Object.values(this.newEntries) // finalEntries 就是你想要的格式:[{ id: '1', amount: '50.00' }, { id: '2', amount: '123.45' }]
方案二:直接用对象数组绑定(更直观)
如果defaultFunds的顺序和你要的数组顺序一致,直接初始化对应数组即可:
- 初始化数据:
data() { return { defaultFunds: [...], newEntries: this.defaultFunds.map(fund => ({ id: fund.id, amount: '' })) } } - 调整模板绑定:v-for带上索引,直接绑定数组对应位置的对象属性
<table class="table m-0"> <tbody> <tr v-for="(fund, index) in defaultFunds" :key="fund.id"> <td> {{fund.name}} <b-input v-model="newEntries[index].id" :value="fund.id" name="entryFund" type="text" class="d-none" /> </td> <td> <b-input v-model="newEntries[index].amount" name="newFundAmount" type="text" placeholder="Amount" /> </td> </tr> </tbody> </table>
这种方式下,newEntries从一开始就是你想要的对象数组结构,不用额外转换。
内容的提问来源于stack exchange,提问作者Jason Ayer
相关产品推荐
相关产品推荐

