vue实现二维数组表格渲染

在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-forv-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元素上绑定keyrowIndex
在内层的v-for中,使用(cell, colIndex) in row的语法来迭代每行中的列数据,并在td元素上绑定keycolIndex

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

温暖前端

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值