1. 程式人生 > 資訊 >極速競賽,特斯拉 Model S Plaid 跑贏兩款最快的油車

極速競賽,特斯拉 Model S Plaid 跑贏兩款最快的油車

問題描述:

  使用antd表格a-table元件時,有時需要展示每條資料的序號。

  通常在columns定義時寫為如下形式:

const columns = [
  {
    title: '序號',
    align: 'center',
    width: 100,
    customRender: (text, record, index) => `${index + 1}`
  }
}

在不設定分頁的情況下,即pagination="false",表格資料單頁顯示,且序號正常

如果需要分頁,配置pagination="true"(預設,也可以不寫),會導致切換頁面後序號重新從1開始

很明顯,我們期待上圖中第二頁序號應從11開始,因此只要拿到currentPagepageSize,便可以計算當前頁的正確序號。

解決方法:

  配置pagination物件,【序號】書寫為插槽形式。

1、data中定義pagination:

pagination: {
    current: 1,
    defaultCurrent: 1,
    pageSize: 10,
    onChange: this.onPageChange.bind(this)
}

2、method中增加onPageChange方法:

onPageChange (current) {
     this.pagination.current = current
}

3、【序號】書寫為插槽形式:

const columns = [
  {
    title: '序號',
    align: 'center',
    width: 200,
    scopedSlots: { customRender: 'dataIndex' }
  }
]

4、table元件配置:

<a-table
    :columns="columns"
    :dataSource="dataSource"
    bordered
    :pagination="pagination"
    :rowKey="(record, index) => index"
    :loading="tableLoading">
    <template slot="dataIndex" slot-scope="text, record, index">
      <span>{{ (pagination.current - 1) * pagination.pageSize + index + 1 }}</span>
    </template>
</a-table>