Vue.js 表格渲染:如何在指定行下方插入数据
<h2>Vue.js 表格渲染:如何在指定行下方插入数据</h2>
<p>本文将介绍如何使用 Vue.js 在 HTML 表格的指定行下方插入数据。假设你有一个 <code>tableData</code> 数组,其中每个对象都包含一个 <code>cardList</code> 数组,需要将 <code>cardList</code> 中的数据渲染到对应行的下方。</p>
<h3>代码示例</h3>
<p>以下是实现该功能的 Vue.js 代码:html<template> <table id='myTable'> <tr> <th>时间</th> <th>姓名</th> <th>地址</th> </tr> <tbody> <tr v-for='item in tableData' :key='item.id' class='style'> <td>{{ item.date }}</td> <td>{{ item.name }}</td> <td>{{ item.address }}</td> </tr> <tr v-for='card in item.cardList' :key='card.cardId'> <td></td> <td>{{ card.cardName }}</td> <td></td> </tr> </tbody> </table></template></p>
<script>export default { name: 'TableMerge', data() { return { checked: false, tableData: [ { id: 1, date: '2016-05-03', name: '王小虎', address: '上海市普陀区金沙江路 1518 弄', cardList: [ { cardName: '测试', cardStatus: 'success', cardSize: 'big', cardId: 100, }, { cardName: '测试', cardStatus: 'success', cardSize: 'big', cardId: 101, }, { cardName: '测试', cardStatus: 'success', cardSize: 'big', cardId: 102, }, { cardName: '测试', cardStatus: 'success', cardSize: 'big', cardId: 103, }, ], }, { id: 5, date: '2016-05-08', name: '王小虎', address: '上海市普陀区金沙江路 1518 弄', }, ], }; }, methods: {},};</script>
<style scoped>table { border-collapse: collapse;}th,td { padding: 10px; width: 200px; border: 1px #c4c7ce solid; text-align: center;}</style>
<h3>代码解析</h3>
<ol>
<li><strong>嵌套 <code>v-for</code></strong>: 我们使用两个嵌套的 <code>v-for</code> 指令来遍历数据。外层 <code>v-for</code> 遍历 <code>tableData</code> 数组,渲染主要的表格行。内层 <code>v-for</code> 遍历每个 <code>item</code> 的 <code>cardList</code>,并将 <code>cardName</code> 渲染到对应行的下方。2. <strong><code>:key</code> 属性</strong>: 为每个 <code><tr></code> 元素绑定唯一的 <code>:key</code> 属性,帮助 Vue.js 更高效地更新 DOM。3. <strong>样式</strong>: 代码中包含简单的 CSS 样式,用于设置表格边框、单元格 padding 和文本对齐方式。</li>
</ol>
<p>通过以上代码,你可以轻松地在 Vue.js 中实现将嵌套数据渲染到指定表格行的下方。</p>
原文地址: https://www.cveoy.top/t/topic/fw7P 著作权归作者所有。请勿转载和采集!