You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VueJS问题:修改输入/选择框时如何更新对应变量

问题解决:Vue表单无法同步更新数组对象属性

你的问题核心在于单向绑定与双向绑定的差异:

  • 你使用的:value是单向数据绑定:它仅负责把ingredient.quantite/ingredient.unite的值渲染到表单元素中,但不会监听用户的输入操作,自然无法将修改同步回selected_ingredients数组。
  • 要实现数据与表单的双向同步,必须使用Vue提供的v-model指令。

修改后的核心代码:

<div
    v-for="(ingredient) in selected_ingredients"
    :key="ingredient.uuid"
>
    <!-- 替换:value为v-model实现双向绑定 -->
    <input
        type="text"
        v-model="ingredient.quantite"
    >

    <select
        v-model="ingredient.unite"
    >
        <option
            v-for="unite in liste_unites"
            :key="unite"
            :value="unite"
        >{{ unite }}</option>
    </select>
</div>

补充说明:

如果你的selected_ingredients是后续动态添加的对象(非初始化时就存在于数组中),需确保新对象的属性是响应式的。添加新食材时直接按完整结构推入数组即可:

// 响应式添加新食材的示例
this.selected_ingredients.push({
  uuid: '新的唯一标识',
  nom: '新食材名称',
  quantite: '0',
  unite: 'g'
});

Vue会自动对数组中已存在的对象属性做响应式监听,只要对象初始化时包含quantite和unite字段,使用v-model就能直接实现数据同步。

内容的提问来源于stack exchange,提问作者Elodie G.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 23:50:28