Vue 表格嵌套表格实现方法 - 详细教程
在Vue中,可以使用嵌套组件的方式来实现表格嵌套表格的效果。以下是一个简单的示例:\n\n首先,定义一个父组件,用于渲染表格和子表格:\nvue\n<template>\n <table>\n <thead>\n <tr>\n <th>姓名</th>\n <th>年龄</th>\n <th>子表格</th>\n </tr>\n </thead>\n <tbody>\n <tr v-for="item in items" :key="item.id">\n <td>{{ item.name }}</td>\n <td>{{ item.age }}</td>\n <td>\n <child-table :data="item.children"></child-table>\n </td>\n </tr>\n </tbody>\n </table>\n</template>\n\n<script>\nimport ChildTable from './ChildTable.vue';\n\nexport default {\n components: {\n ChildTable\n },\n data() {\n return {\n items: [\n {\n id: 1,\n name: '张三',\n age: 20,\n children: [\n {\n id: 1,\n name: '子表格数据1',\n age: 10\n },\n {\n id: 2,\n name: '子表格数据2',\n age: 15\n }\n ]\n },\n {\n id: 2,\n name: '李四',\n age: 25,\n children: [\n {\n id: 3,\n name: '子表格数据3',\n age: 12\n },\n {\n id: 4,\n name: '子表格数据4',\n age: 18\n }\n ]\n }\n ]\n };\n }\n};\n</script>\n\n\n然后,在父组件中引入并定义一个子组件,用于渲染子表格的内容:\nvue\n<template>\n <table>\n <thead>\n <tr>\n <th>姓名</th>\n <th>年龄</th>\n </tr>\n </thead>\n <tbody>\n <tr v-for="item in data" :key="item.id">\n <td>{{ item.name }}</td>\n <td>{{ item.age }}</td>\n </tr>\n </tbody>\n </table>\n</template>\n\n<script>\nexport default {\n props: {\n data: {\n type: Array,\n required: true\n }\n }\n};\n</script>\n\n\n最后,在需要使用嵌套表格的地方,引入父组件即可:\nvue\n<template>\n <div>\n <h1>表格嵌套表格示例</h1>\n <parent-table></parent-table>\n </div>\n</template>\n\n<script>\nimport ParentTable from './ParentTable.vue';\n\nexport default {\n components: {\n ParentTable\n }\n};\n</script>\n\n\n以上示例中,父组件中的一个表格行对应一个数据项,通过v-for循环渲染出多个表格行。每个表格行的子表格使用子组件ChildTable来渲染,通过props来传递子表格的数据。子组件中也是使用v-for来渲染子表格的内容。\n\n这样就实现了一个简单的表格嵌套表格的效果。当然,具体的实现方式还可以根据实际需求进行调整和扩展。
原文地址: https://www.cveoy.top/t/topic/qatK 著作权归作者所有。请勿转载和采集!