【问题标题】:Create dynamic table component Vue JS创建动态表格组件Vue JS
【发布时间】:2019-03-31 02:42:29
【问题描述】:

我正在学习 Vue JS。我想创建一个组件来显示可以在其他组件中重用的表格数据。我有 2 个道具项目(数据)和列(列名)

items: [
        {
            'id':'1',
            'title': 'hello',
            'description': 'ok ok',
            'created_date': '2018-09-09'
        },
        {
            'id':'2',
            'title': 'hello 2',
            'description': 'ok ok 2',
            'created_date': '2018-10-09'
        }
    ],
    columns: [ 'id', 'title', 'description', 'created_date']

我想创建一个如下表

<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>

我不知道如何按列名从项目中获取价值。是否可以创建这样的表?

【问题讨论】:

  • 您也可以使用Object.keys 来获取列,而不是传入两个道具,如下所示:&lt;th v-for="(column, index) in Object.keys(items)" :key="index"&gt;{{column}}&lt;/th&gt;

标签: javascript html vue.js


【解决方案1】:

一切都很好,只需将模板 item.$column 中的值更改为 item[column]

   <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>

【讨论】:

    猜你喜欢
    • 2019-03-20
    • 1970-01-01
    • 2020-02-29
    • 1970-01-01
    • 1970-01-01
    • 2015-09-06
    • 1970-01-01
    • 2020-02-22
    • 2019-07-12
    相关资源
    最近更新 更多