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

相关推荐
Larcher26 分钟前
新手也能学会,100行代码玩AI LOGO
前端·llm·html
徐子颐38 分钟前
从 Vibe Coding 到 Agent Coding:Cursor 2.0 开启下一代 AI 开发范式
前端
小月鸭1 小时前
如何理解HTML语义化
前端·html
jump6801 小时前
url输入到网页展示会发生什么?
前端
诸葛韩信1 小时前
我们需要了解的Web Workers
前端
brzhang1 小时前
我觉得可以试试 TOON —— 一个为 LLM 而生的极致压缩数据格式
前端·后端·架构
yivifu2 小时前
JavaScript Selection API详解
java·前端·javascript
这儿有一堆花2 小时前
告别 Class 组件:拥抱 React Hooks 带来的函数式新范式
前端·javascript·react.js
十二春秋2 小时前
场景模拟:基础路由配置
前端
六月的可乐2 小时前
实战干货-Vue实现AI聊天助手全流程解析
前端·vue.js·ai编程