Vue3动态表格仅提交首行数据至Laravel控制器问题求助
问题
在Vue3 + Inertia.js项目中,我通过以下代码实现动态输入表格,但提交到Laravel控制器时,仅能传递首行数据,无法传递完整的输入数组。
<script setup> import { Head, Link, useForm } from '@inertiajs/inertia-vue3'; import Checkbox from '@/Components/Checkbox.vue'; import { createApp } from 'vue' import InputError from '@/Components/InputError.vue'; import InputLabel from '@/Components/InputLabel.vue'; import PrimaryButton from '@/Components/PrimaryButton.vue'; import TextInput from '@/Components/TextInput.vue'; const form1 = useForm({ items: { srno: '', remarks: [], } }); defineProps({ form:useForm }); </script> <script> export default { data() { return { tableRows: [ { "id": 1, remarks: '', } ] } }, methods: { insert_Row() { this.tableRows.push( { "id": this.tableRows.length+1, remarks: '', } ) } } } </script> <template> <table> <thead> <tr> <th>Sr#</th> <th>Remarks</th> </tr> </thead> <tbody> <tr v-for="(item, index) in tableRows" :key="item.id"> <td>{{item.id}}</td> <td><input type="text" v-model="item.remarks" @input="form.remarks = $event.target.value"></td> </tr> </tbody> </table> <button @click="insert_Row">Add row +</button> </template>

问题分析
- API风格混合:同时使用
<script setup>和选项式API,导致状态管理混乱,form1和模板中用到的form未正确关联。 - Form结构错误:
form1中的items被定义为单个对象,而非数组,无法存储多行数据;且单个item里的remarks设为数组不符合需求,每个行的remarks应为字符串。 - 数据绑定错误:输入框的
@input每次都会将form.remarks覆盖为当前输入值,而非收集所有行的remarks到数组;tableRows和Inertia form未同步,提交时自然无法传递完整数据。
解决方案
统一使用<script setup>,调整form结构并正确绑定动态行数据:
<script setup> import { useForm } from '@inertiajs/inertia-vue3'; import PrimaryButton from '@/Components/PrimaryButton.vue'; // 初始化form,items为数组,每个item包含id和remarks const form = useForm({ items: [ { id: 1, remarks: '' } ] }); // 添加行的方法 const insertRow = () => { const newId = form.items.length + 1; form.items.push({ id: newId, remarks: '' }); }; // 提交方法(示例) const submitForm = () => { form.post('/your-submit-url'); }; </script> <template> <table> <thead> <tr> <th>Sr#</th> <th>Remarks</th> </tr> </thead> <tbody> <!-- 直接遍历form.items,v-model绑定到对应item的remarks --> <tr v-for="(item, index) in form.items" :key="item.id"> <td>{{ item.id }}</td> <td><input type="text" v-model="item.remarks"></td> </tr> </tbody> </table> <button @click="insertRow">Add row +</button> <PrimaryButton @click="submitForm">提交</PrimaryButton> </template>
关键修改说明
- 统一API风格:完全使用
<script setup>,避免状态分散。 - 修正Form结构:将
items设为数组,每个元素对应一行数据,结构与动态行匹配。 - 直接绑定Form数据:遍历
form.items而非独立的tableRows,v-model直接绑定到form内的字段,确保输入数据实时同步到Inertia的form中。 - 简化添加行逻辑:直接向
form.items中push新对象,无需维护额外的tableRows数组。
修改后,提交表单时form.items会作为完整数组传递到Laravel控制器,可通过$request->input('items')获取所有行的remarks数据。
内容的提问来源于stack exchange,提问作者Muhammad Muazzam
相关产品推荐
相关产品推荐

