vue实现二维数组表格渲染

在Vue中渲染二维数组表格可以采用嵌套的<template>v-for指令。

写法一

html 复制代码
<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指令来渲染二维数组。

html 复制代码
<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

相关推荐
芜青43 分钟前
HTML+CSS:浮动详解
前端·css·html
SchuylerEX1 小时前
第六章 JavaScript 互操(2).NET调用JS
前端·c#·.net·blazor·ui框架
东风西巷2 小时前
Rubick:基于Electron的开源桌面效率工具箱
前端·javascript·electron·软件需求
探码科技2 小时前
AI知识管理软件推荐:九大解决方案与企业应用
前端·ruby
编程小黑马2 小时前
解决flutter 在控制器如controller 无法直接访问私有类方法的问题
前端
Miracle_G3 小时前
每日一个知识点:JavaScript 箭头函数与普通函数比较
javascript
unfetteredman3 小时前
Error: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.32' not found
前端·javascript·vite
云存储小精灵3 小时前
Dify x 腾讯云 COS MCP:自然语言解锁智能数据处理,零代码构建 AI 新世界
前端·开源
山间板栗3 小时前
微信小程序环境变量设置方案
前端
电商API大数据接口开发Cris3 小时前
Java Spring Boot 集成淘宝 SDK:实现稳定可靠的商品信息查询服务
前端·数据挖掘·api