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

相关推荐
QQ1__8115175157 小时前
Spring boot名城小区物业管理系统信息管理系统源码-SpringBoot后端+Vue前端+MySQL【可直接运行】
前端·vue.js·spring boot
钛态7 小时前
前端微前端架构:大项目的救命稻草还是自找麻烦?
前端·vue·react·web
一粒黑子7 小时前
【实战解析】阿里开源 PageAgent:纯前端 GUI Agent,一行JS让网页支持自然语言操控
前端·javascript·开源
独角鲸网络安全实验室7 小时前
2026微信小程序抓包全解析:从实操落地到合规风控,解锁前端调试新范式
前端·微信小程序·小程序·抓包·系统代理绕过·https证书严格校验·进程隔离
紫微AI7 小时前
前端文本测量成了卡死一切创新的最后瓶颈,pretext实现突破了
前端·人工智能·typescript
GISer_Jing7 小时前
AI前端(From豆包)
前端·aigc·ai编程
IT枫斗者7 小时前
前端部署后如何判断“页面是不是最新”?一套可落地的版本检测方案(适配 Vite/Vue/React/任意 SPA)
前端·javascript·vue.js·react.js·架构·bug
测试修炼手册7 小时前
[测试技术] 深入理解 JSON Web Token (JWT)
前端·json
AI老李7 小时前
2026 年 Web 前端开发的 8 个趋势!
前端
里欧跑得慢7 小时前
15. Web可访问性最佳实践:让每个用户都能平等访问
前端·css·flutter·web