vue3中实现动态行列表格

114 阅读1分钟

image.png

<template>
  <div>
    <h2>产品指标额</h2>
    <table>
      <thead>
        <tr>
          <th></th>
          <th>产品</th>
          <th v-for="product in products" :key="product.name">{{ product.name }}</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="month in months" :key="month">
          <td>{{ month }}</td>
          <td v-for="product in products" :key="product.name">{{ product.values[month] }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>
<script>
export default {
  data() {
    return {
      months: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
      products: [
        {
          name: '格华止',
          values: {
            '1月': '782K',
            '2月': '1523K',
            '3月': '782K',
            '4月': '774K',
            '5月': '782K',
            '6月': '787K',
            '7月': '1039K',
            '8月': '958K',
            '9月': '1048K',
            '10月': '1077K',
            '11月': '1177K',
            '12月': '958K'
          }
        },
        {
          name: '优甲乐',
          values: {
            '1月': '33K',
            '2月': '67K',
            '3月': '33K',
            '4月': '34K',
            '5月': '33K',
            '6月': '35K',
            '7月': '63K',
            '8月': '601K',
            '9月': '69K',
            '10月': '77K',
            '11月': '78K',
            '12月': '60K'
          }
        }
      ]
    };
  }
};
</script>
  • 数据定义:在 data 中定义了固定的 months 数组和动态的 products 数组。每个产品包含 namevalues,其中 values 是一个以月份为键的对象,存储每个月的值。

  • 表头生成:使用 v-for 指令遍历 products 数组生成产品名称列。

  • 表格内容生成:外层 v-for 遍历 months 数组生成每一行,内层 v-for 遍历 products 数组生成每个产品的值。

  • 样式:使用简单的 CSS 样式来美化表格。