在Vue中渲染二维数组表格可以采用嵌套的<template>
和v-for
指令。
写法一
<template> <table> <thead> <tr> <th v-for="(header, index) in headers" :key="index">{{ header }}</th> </tr> </thead> <tbody> <tr v-for="(row, rowIndex) in tableData" :key="rowIndex"> <td v-for="(cell, cellIndex) in row" :key="cellIndex">{{ cell }}</td> </tr> </tbody> </table>
</template>
<script>
export default { data() { return { headers: ['Name', 'Age', 'City'], tableData: [ ['John', 25, 'New York'], ['Jane', 31, 'London'], ['Alice', 19, 'Paris'] ] }; }
};
</script>
使用headers
数组定义表头,而tableData
数组则表示表格的数据。v-for
指令用于遍历headers
数组和tableData
数组,并使用:key
绑定唯一的标识符。在表格的<thead>
和<tbody>
标签内部,我们使用嵌套的v-for
指令生成表头和表格行,并在每个单元格中显示对应的值。
写法二
使用v-for
和v-bind:key
指令来渲染二维数组。
<template> <table> <tr v-for="(row, rowIndex) in tableData" :key="rowIndex"> <td v-for="(cell, colIndex) in row" :key="colIndex"> {{ cell }} </td> </tr> </table>
</template>
<script>
export default { data() { return { tableData: [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] }; }
};
</script>
使用Vue 3的组合式API。在模板中,使用嵌套的v-for
指令来遍历二维数组。外层的v-for
指令遍历行,内层的v-for
指令遍历每行中的列。
对于每个行,使用(row, rowIndex) in tableData
的语法来迭代二维数组中的行数据,并在tr
元素上绑定key
为rowIndex
。
在内层的v-for
中,使用(cell, colIndex) in row
的语法来迭代每行中的列数据,并在td
元素上绑定key
为colIndex
。