【问题标题】:Dynamically create html table from an Array从数组动态创建 html 表
【发布时间】:2021-07-24 04:55:39
【问题描述】:

嘿,我对 Vue 和 JavaScript 还很陌生,我想创建一个 Html 表。对于我的软件,我想要一个 Table.vue 组件,它可以向我显示不同的表格,如下所示。

   {
        "id": 1,
        "text": "Hello"
   }
   {
        "id": 1,
        "status": "damaged",
        "info": "test",
        "text": "content"

   }

如何动态获取这些不同表格的列以及如何显示它们?

<template>
  <table class="table">
      <thead>
          <tr>
              <th v-for="(column, index) in columns" :key="index"> {{column}}</th>
          </tr>
      </thead>
      <tbody>
          <tr v-for="(item, index) in items" :key="index">
              <td v-for="(column, indexColumn) in columns" :key="indexColumn">{{item[column]}}</td>
          </tr>
      </tbody>
    </table>
</template>
 data() {
        return {
            items: [],
            columns: []
        }
    }

table example

【问题讨论】:

    标签: javascript html arrays vue.js


    【解决方案1】:

    您需要指定应呈现的列以及包含所有数据的行。

    Table.vue 可能如下所示:

    <template>
      <table>
        <thead>
          <tr>
            <th v-for="(column, index) in columns" :key="index">
              {{ column }}
            </th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(row, index) in rows" :key="index">
            <td v-for="(column, index) in columns" :key="index">
              {{ row[column] }}
            </td>
          </tr>
        </tbody>
      </table>
    </template>
    
    <script>
    export default {
      name: "Table",
      props: {
        columns: Array,
        rows: Array,
      },
    };
    </script>
    

    ...然后父组件会将数据传递给Table.vue,如下所示:

    <template>
      <Table :columns="columns" :rows="rows" />
    </template>
    
    <script>
    import Table from "./components/Table";
    
    export default {
      name: "App",
      components: {
        Table,
      },
      data() {
        return {
          columns: ["id", "title", "description"],
          rows: [
            {
              id: 1,
              title: "what is this",
              description: "i like to describe",
            },
            {
              id: 2,
              title: "wait wat?",
              description: "i like to describe, too",
            },
          ],
        };
      },
    };
    </script>
    

    请参阅working codesandbox

    请注意,出于性能原因,大多数实际的 Vue dataTable 组件使用render functions

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-05
      • 2012-03-21
      • 2014-08-02
      • 1970-01-01
      • 2017-01-23
      • 2011-07-06
      • 2011-05-20
      相关资源
      最近更新 更多