首页 > 解决方案 > 动态 Vue 表

问题描述

我正在尝试在 Vue 中创建一个动态表,但我正在为我想要显示数据的方式而苦苦挣扎。

这是我从 API 中得到的:(还有更多值,但我会保持简单。)

{id: 1, descricao: 'Ambiente 01', valor: "12.5"}
{id: 2, descricao: 'Ambiente 02', valor: "5.5"}
{id: 3, descricao: 'Ambiente 03', valor: "-2.5"}
{id: 4, descricao: 'Ambiente 01', valor: "12.2"}
{id: 5, descricao: 'Ambiente 02', valor: "5.2"}
{id: 6, descricao: 'Ambiente 03', valor: "-2.3"}
{id: 7, descricao: 'Ambiente 01', valor: "11.9"}
{id: 8, descricao: 'Ambiente 02', valor: "5.7"}
{id: 9, descricao: 'Ambiente 03', valor: "-2.8"}

这是我的 vue 组件的样子:

<template>  
  <table class="table">
    <thead class="thead-light">
      <tr>
        <th v-for="(dados, descricao) in agrupaDados" :key="dados.id">
          {{ descricao }}
        </th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="dados in agrupaDados" :key="dados.id">
        <td v-for="row in dados" :key="row.id">
          {{ row.valor }}
        </td>
      </tr>
    </tbody>
  </table>
</template>
<script>
  export default {
    props: [
      'dados'
    ],
    computed: {
      agrupaDados() {
        return _.groupBy(this.dados, 'descricao');
      }
    }   
  }
</script>

这就是我的桌子的样子: 桌子

问题是每列对应的数据都显示在一行中,我不知道如何更改它。为了更好地解释它,我将尝试说明我得到的结果和我想要得到的结果......

What I have...

Ambiente 01 | Ambiente 02 | Ambiente 03
---------------------------------------
12.5        | 12.2        | 11.9
---------------------------------------
5.5         | 5.2         | 5.7
---------------------------------------    
-2.5        | -2.3        | -2.8

What I want...

Ambiente 01 | Ambiente 02 | Ambiente 03
---------------------------------------
12.5        | 5.5         | -2.5
---------------------------------------
12.2        | 5.2         | -2.3
---------------------------------------    
11.9        | 5.7         | -2.8

如果有人向我解释如何实现这一目标,我将不胜感激。

提前致谢!

标签: vue.js

解决方案


<tbody>
    <tr v-for="index in (data.length / 3)">
      <td>{{ data[3 * (index - 1)].valor }}</td>
      <td>{{ data[3 * (index - 1) + 1].valor }}</td>
      <td>{{ data[3 * (index - 1) + 2].valor }}</td>
    </tr>
</tbody>

data.length / 3因为你有 3 个不同的列。

data像这样的元素数组在哪里:

data: [
    { id: 1, descricao: "Ambiente 01", valor: "12.5" },
    { id: 2, descricao: "Ambiente 02", valor: "5.5" },
    { id: 3, descricao: "Ambiente 03", valor: "-2.5" },
    { id: 4, descricao: "Ambiente 01", valor: "12.2" },
    { id: 5, descricao: "Ambiente 02", valor: "5.2" },
    { id: 6, descricao: "Ambiente 03", valor: "-2.3" },
    { id: 7, descricao: "Ambiente 01", valor: "11.9" },
    { id: 8, descricao: "Ambiente 02", valor: "5.7" },
    { id: 9, descricao: "Ambiente 03", valor: "-2.8" }
]

推荐阅读