微信公众号: [大前端驿站]
关注大前端驿站。问题或建议,欢迎公众号留言。前端
这是我参与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
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方式的效果
【分享、点赞、在看】三连吧,让更多的人加入咱们