Vue JS 创建动态表格组件

use*_*303 6 html javascript vue.js

我正在学习 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']
Run Code Online (Sandbox Code Playgroud)

我想创建一个如下表

<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>
Run Code Online (Sandbox Code Playgroud)

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

小智 11

一切都很好,只需将模板 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>
Run Code Online (Sandbox Code Playgroud)