Vue3+Inertia开发如何将props的units数组绑定到reactive表单的v-model
Vue3+Inertia表单units数组多值绑定解决方案
你当前的写法硬编码了units数组仅有1个对象,无法匹配props中invoice.units的多值场景,同时代码中的data (props)写法不符合Vue规范,Vue3场景下需使用setup函数接收props参数,修正后的完整代码如下:
修正后的Script代码
import { reactive } from 'vue' import { Inertia } from '@inertiajs/inertia' export default { props: { invoice: { type: Object, required: true } }, setup(props) { const form = reactive({ invoice_code: props.invoice.invoice_code, customer_name: props.invoice.customer_name, // 核心修改:遍历props中所有unit生成响应式数组 units: props.invoice.units.map(unit => ({ id: unit.id, unit_quantity: unit.unit_quantity, unit_type: unit.unit_type, unit_name: unit.unit_name, unit_description: unit.unit_description, unit_completeness: unit.unit_completeness, unit_cost: unit.unit_cost, })) }) function update () { Inertia.put(`/invoice/${props.invoice.id}`, form) } // 可选扩展:新增unit项方法 function addUnit() { form.units.push({ unit_quantity: 1, unit_type: 'Other', unit_name: '', unit_description: '', unit_completeness: '', unit_cost: 0 }) } // 可选扩展:删除指定unit项方法 function removeUnit(index) { form.units.splice(index, 1) } return { form, update, addUnit, removeUnit } } }
修正后的模板代码
<table> <tr> <th>Qty</th> <th>Unit</th> <th>Unit Name</th> <th>Description</th> <th>Completeness</th> <th>Cost</th> <!-- 可选:操作列 --> <th>操作</th> </tr> <!-- 修正key值兜底逻辑,避免无id时渲染异常 --> <tr v-for="(unit, index) in form.units" :key="unit.id ?? index"> <td> <input type="number" v-model="unit.unit_quantity"> </td> <td> <select v-model="unit.unit_type"> <option value="Camera">Camera</option> <option value="Phone">Phone</option> <option value="Laptop-PC">Laptop-PC</option> <option value="Other">Other</option> </select> </td> <td> <input type="text" v-model="unit.unit_name"> </td> <td> <input type="text" v-model="unit.unit_description"> </td> <td> <input type="text" v-model="unit.unit_completeness"> </td> <td> <input type="number" v-model="unit.unit_cost"> </td> <!-- 可选:删除按钮 --> <td> <button type="button" @click="removeUnit(index)">删除</button> </td> </tr> </table> <!-- 可选:新增按钮 --> <button type="button" @click="addUnit">新增商品项</button> <button type="button" @click="update">提交保存</button>
注意事项
- 初始化units时使用
map遍历props中的所有unit项,完整拷贝属性生成新数组,不要直接引用props中的对象,避免触发只读props修改警告 - reactive对象的数组原生方法(push/splice等)本身支持响应式,新增、删除操作可正常触发视图更新,v-model绑定不会失效
- key值使用
unit.id ?? index做兜底,适配部分unit无id的场景
内容的提问来源于stack exchange,提问作者alvinnn
相关产品推荐
相关产品推荐

