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

相关推荐
Data_agent几秒前
实战:用Splash搞定JavaScript密集型网页渲染
开发语言·javascript·ecmascript
Shaneyxs10 分钟前
从 0 到 1 实现CloudBase云开发 + 低代码全栈开发活动管理小程序(13)
前端
半山烟雨半山青11 分钟前
微信内容emoji表情包编辑器 + vue3 + ts + WrchatEmogi Editor
前端·javascript·vue.js
码途潇潇13 分钟前
Vue 事件机制全面解析:原生事件、自定义事件与 DOM 冒泡完全讲透
前端·javascript
zmirror14 分钟前
Monorepo 在 Docker 中的构建方案方案
前端
用户479492835691525 分钟前
node_modules 太胖?用 Node.js 原生功能给依赖做一次大扫除
前端·后端·node.js
_Kayo_36 分钟前
TypeScript 学习笔记2
前端·javascript·typescript
海纳百川本尊7606438 分钟前
Flutter框架核心原理深度解析
前端
Shaneyxs38 分钟前
从 0 到 1 实现CloudBase云开发 + 低代码全栈开发活动管理小程序(12)
前端