具有动态列的元素 UI 表

Bug*_*ddy 4 vue.js vuejs2 element-ui

我正在寻找一个使用 Element UI 表组件而不必对所有列进行硬编码的示例。我见过的所有示例,包括官方 Element UI 表文档,都显示了模板中指定的每一列。

我正在尝试做这样的事情。在我的旧表格组件中,这为我提供了所有列和带有delete按钮的额外结束列。

<template>
  <div v-if="tableData.length > 0">
    <b-table striped hover v-bind:items="tableData" :fields=" keys.concat(['actions']) ">
      <template slot="actions" slot-scope="row">
        <b-btn size="sm" @click.stop="tableClick(row.item)" class="mr-1">
          Delete
        </b-btn>
      </template>
    </b-table>
  </div>
</template>
Run Code Online (Sandbox Code Playgroud)

相比之下,Element UI Table 示例都使用多个重复的el-table-column标签。由于在运行时加载具有不同列的数据,我无法使用这种方法。

  <template>
    <el-table
      :data="tableData"
      style="width: 100%">
      <el-table-column
        prop="date"
        label="Date"
        width="180">
      </el-table-column>
      <el-table-column
        prop="name"
        label="Name"
        width="180">
      </el-table-column>
      <el-table-column
        prop="address"
        label="Address">
      </el-table-column>
    </el-table>
  </template>
Run Code Online (Sandbox Code Playgroud)

我是一个初学者,正在努力理解如何使用 el-table 实现我的目标。

小智 10

您可以将列作为具有所需属性的对象数组,并使用v-for以下命令在模板中迭代它们:

<template>
    <el-table
          :data="tableData"
          style="width: 100%">
        <el-table-column v-for="column in columns" 
                         :key="column.label"
                         :prop="column.prop"
                         :label="column.label"
                         :formatter="column.formatter"
                         :min-width="column.minWidth">
        </el-table-column>
        <el-table-column fixed="right">
            <template slot-scope="scope">
              ... your delete button or whatever here...
            </template>
    </el-table-column>
    </el-table>
</template>
Run Code Online (Sandbox Code Playgroud)

然后你从某个地方获取你的列,它们可能在数据中,例如:

data() {
    return {
      columns: [
        {
          prop: 'date',
          label: 'Date',
          minWidth: 180px
        },
        {
          prop: 'name',
          label: 'Name',
          minWidth: 180px
        },
        {
          prop: 'address',
          label: 'Address',
          formatter: (row, col, cell, index) => this.addressFormatter(cell),  //example of a formatter
        },
      ],
    };
},
Run Code Online (Sandbox Code Playgroud)