要在 Vue 3 中创建一个包含嵌套 el-table
和 el-form-item
的 el-form
,并且使用动态 prop
来绑定表单字段,我们需要整合你之前提到的 findPath
函数。此外,我们还需要确保 el-form-item
正确引用了 el-table
中每行数据的路径。
以下是一个完整的 Vue 3 示例,展示了如何结合这些元素:
-
findPath
函数:用于找到特定 ID 在数据结构中的路径。 -
el-form
和el-table
组合:在表单中嵌套表格,并在表格中使用表单项。 -
动态
prop
绑定:使用findPath
函数返回的路径动态设置el-form-item
的prop
。<template> <el-form :model="form"> <el-table :data="form.tableData"> <el-table-column label="Name"> <template #default="scope"> <el-form-item :prop="'tableData' + findPath(form.tableData, scope.row.id) + '.name'"> <el-input v-model="scope.row.name"></el-input> </el-form-item> </template> </el-table-column> <!-- 添加其他列 --> </el-table> </el-form> </template> <script> export default { data() { return { form: { tableData: [ { id: "1", name: "Item 1", children: [ { id: "1-1", name: "Child Item 1-1", children: [], }, // 其他子项... ], }, // 其他项... ], }, }; }, methods: { findPath(obj, targetId, path = []) { if (Array.isArray(obj)) { for (let i = 0; i < obj.length; i++) { const result = this.findPath(obj[i], targetId, path.concat([`.children[${i}]`])); if (result) return result; } } else if (typeof obj === 'object' && obj !== null) { if (obj.id === targetId) return path.join(''); if (obj.children) { const result = this.findPath(obj.children, targetId, path.concat('.children')); if (result) return result; } } return ''; }, }, }; </script> <style> /* 你的样式 */ </style>