Ant Design Vue實現Table增長合計行

微信公衆號:  [大前端驛站]
關注大前端驛站。問題或建議,歡迎公衆號留言。前端

這是我參與8月更文挑戰的第9天,活動詳情查看:8月更文挑戰web

背景

最近遇到一個需求,須要在表格的末尾增長合計行,項目用的是Vue2.0搭建的,UI框架使用的是Ant Design Vue,因此第一步是去官網看了一下有沒有合適的範例,很遺憾沒有。而後開始百度是否有相關的博客文章,發現了一篇React項目相關的文章寫得還不錯,給予了大體的思路。本着積累知識的原則,咱們仍是把它用Vue的方式記錄一遍。後端

實現需求

方案一:

合計的數據通常來講後端計算好傳給前端,咱們須要作的就是將合計的數據增長到表格數據的最後,合計行將會以table的body形式展示出來數組

這個比較簡單,直接上代碼微信

<template>
  <a-table :columns="columns" :data-source="data" />
</template>
<script>
const columns = [
  {
    title: '序號',
    dataIndex: 'key',
  },
  {
    title: 'Name',
    dataIndex: 'name',
  },
  {
    title: 'Age',
    dataIndex: 'age',
  },
  {
    title: 'Address',
    dataIndex: 'address',
  },
];

const data = [];
for (let i = 0; i < 5; i++) {
  data.push({
    key: i+1,
    name: `Edward King ${i}`,
    age: 32,
    address: `London, Park Lane no. ${i}`,
  });
}

// 只須要在數據的末尾push一份合計的數據便可
data.push({
  key: '合計',
  name: '',
  age: 1000,
  address: '',
})

export default {
  data() {
    return {
      data,
      columns,
      selectedRowKeys: [], // Check here to configure the default column
    };
  }
};
</script>
複製代碼

效果以下markdown

table01.png

方案二:

Ant Design Vue 提供了一個table的footer屬性,咱們藉助這個屬性來實現框架

構建合計數據dom

computed: {
  footerDataSource () {
    const summary = Object.assign({}, this.data[0])
    for (const attr in summary) {
      summary[attr] = '合計'
      break
    }
    return [summary]
  }
}
複製代碼

合計的數據通常是後端提供的,可是須要構建成原表的一行數據類似的數據,我這裏直接用了data數據的第一行作爲例子,而後將序號列的值改成'合計',這裏要注意footerDataSource也是一個數組類型,由於footer的原理就是加入的另一個Table函數

footer是一個函數或者slot-scope, 函數返回的是另一個表格post

handleFooter () {
  return (
    <a-table
      rowKey={Math.random}
      bordered={false}
      pagination={false}
      columns={columns}
      dataSource={this.footerDataSource || []}
      showHeader={false}
    ></a-table>
  )
}
複製代碼

這個表格的屬性columns和原表相同,footerDataSource是後端傳遞的合計的數據

綁定footer屬性

<template>
  <a-table :columns="columns" :data-source="data" :footer="handleFooter" />
</template>
複製代碼

注意:footer建立的是一個table,因此會出現跟原表格出現對不齊的情況,這時候咱們須要將數據的每一項的width須要固定死,默認width='auto'。

const columns = [
  {
    title: '序號',
    dataIndex: 'key',
    width: '25%'
  },
  {
    title: 'Name',
    dataIndex: 'name',
    width: '25%'
  },
  {
    title: 'Age',
    dataIndex: 'age',
    width: '25%'
  },
  {
    title: 'Address',
    dataIndex: 'address',
    width: '25%'
  },
]
複製代碼

可是一般table的列數是不固定的,並且業務通常包含增長或者刪除列的狀況,因此width通常仍是須要程序去計算,最好的方法是寫在handleFooter方法中

handleFooter () {
  // 處理 width 成百分比, 默認 'auto' 會根據text 計算寬度,形成footer對不齊的狀況
  const columns = this.columns
  columns.forEach(col => {
    col.width = (100 / columns.length) + '%'
  })
  return (
    <a-table
      rowKey={Math.random}
      bordered={false}
      pagination={false}
      columns={columns}
      dataSource={this.footerDataSource || []}
      showHeader={false}
    ></a-table>
  )
}
複製代碼

footer方式的效果

table02.png




~~ 感謝觀看

關注下方【大前端驛站】
讓咱們一塊兒學,一塊兒進步

【分享、點贊、在看】三連吧,讓更多的人加入咱們

相關文章
相關標籤/搜索