【Vue】el-table 簡易表格可篩選列

emdzz發表於2024-06-17

需求實現:

程式碼邏輯:

按鈕控制元件:

<el-popover placement="top-start">
  <el-checkbox-group v-model="checkedColumns" @change="whenColumnBoxChange">
    <div v-for="(col, idx) in optionColumns" :key="`optionColumns${idx}`">
      <el-checkbox :label="col.property">{{ col.label }}</el-checkbox>
    </div>
  </el-checkbox-group>
  <el-button style="float: right;" slot="reference" type="primary" size="mini">列篩選</el-button>
</el-popover>

  

表格元件要追加Ref標記:

 <el-table ref="elTable" v-loading="loading" size="small" stripe :height="tableHeight" :data="tableData">

需要設定的資料物件:

defaultShow: true,
checkedColumns: [],
optionColumns: []

所需方法:

// 當選擇時重新渲染表格
whenColumnBoxChange() { this.$refs['elTable'].doLayout() },
// 判斷該列是否展示 getColumnShowFlag(colIdent) { return this.defaultShow || this.checkedColumns.includes(colIdent) },
// 初始化篩選項,並保證預設正常展示 initialOptionColumnsData() { this.$nextTick(() => { const { columns } = this.$refs['elTable'] this.optionColumns = columns.filter(x => x.property).map(x => { return { id: x.id, label: x.label, property: x.property, flag: true } }) this.checkedColumns = this.optionColumns.map(x => x.property) this.defaultShow = false }) },

  

需要對一個個列進行判斷方法設定:

<el-table-column v-if="getColumnShowFlag('apInAmount')" prop="apInAmount" min-width="120px" label="收入總額(元)" align="right" show-overflow-tooltip>
  <template slot-scope="{ row }">
    {{ transFormAmount(row.apInAmount) }}
  </template>
</el-table-column>

  

相關文章