本文主要是介绍vTable实现多维表格,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
介绍
vTable是字节开发的一款能用来渲染表格的库,是用canvas渲染,避免了传统用dom组件表格的一些问题,能很快的渲染出上万格子的表格。
接下来我将使用vTable构建类似下面的多维表格,其中quantity、sales等是指标。
使用
官网地址:Getting_Started——VisActor/VTable tutorial documents
1、首先下载npm,或者cdn引入vtable,并且准备一个div作为容器。vTable有ListTable(普通表格)和PivotTable(透视表)的区别,我们现在用PivotTable来构建表格。
<script src="https://unpkg.com/@visactor/vtable/dist/vtable.min.js"></script><div id="tableContainer" style="width: 100vw;height:100vh;"></div><script>// 创建 VTable 实例const tableInstance = new VTable.PivotTable(document.getElementById('tableContainer'), option);
</script>
2、准备表格数据
[{"city": "重庆","exist": 1,"sold": 2,"column1": "家具"},{"city": "武汉","column1": "家具","exist": 7,"sold": 8},{"city": "重庆","column1": "家具","exist": 2,"sold": 3},{"city": "武汉","column1": "家具","exist": 8,"sold": 9},{"city": "重庆","column1": "体育器材","exist": 4,"sold": 5},{"city": "武汉","column1": "体育器材","exist": 10,"sold": 11},{"city": "重庆","column1": "体育器材","exist": 6,"sold": 7},{"city": "武汉","column1": "体育器材","exist": 11,"sold": 12}
]
3、构建option。
row和column用来指定行和列,
indicators用来指定指标,
dataConfig用来设置合计、平均值等一些计算,
hideIndicatorName用来设置是否隐藏指标
更多配置请看官网
const records = contentconst option = {records,rows: [{dimensionKey: 'city',title: '城市',}],columns: [{dimensionKey: 'column1',title: '类别',}],indicators: [{indicatorKey: 'exist',title: '现存'},{indicatorKey: 'sold',title: '已售',}],// 设置左上角corner: {titleOnDimension: 'all',//row column all},// hideIndicatorName: true,//隐藏指标名// 设置合计dataConfig: {totals: {row: {showGrandTotals: true,subTotalsDimensions: ['exist'],grandTotalLabel: '合计',},}},widthMode: 'standard'};
完整代码
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><!-- <script src="https://unpkg.com/@visactor/vtable/dist/vtable.min.js"></script> --><script src="./vtable.min.js"></script><style>* {margin: 0;padding: 0;}</style>
</head><body><div id="tableContainer" style="width: 99vw;height:99vh;"></div><script>fetch('./data4.txt').then(res => res.json()).then(res => {console.log(res);let content = resconst records = contentconst option = {records,rows: [{dimensionKey: 'city',title: '城市',}],columns: [{dimensionKey: 'column1',title: '类别',}],indicators: [{indicatorKey: 'exist',title: '现存'},{indicatorKey: 'sold',title: '已售',}],// 设置左上角corner: {titleOnDimension: 'all',//row column all},// hideIndicatorName: true,//隐藏指标名// 设置合计dataConfig: {totals: {row: {showGrandTotals: true,subTotalsDimensions: ['exist'],grandTotalLabel: '合计',},}},widthMode: 'standard'};// 创建 VTable 实例const tableInstance = new VTable.PivotTable(document.getElementById('tableContainer'), option);})</script>
</body></html>
效果
现存和已售是指标。
最后附上效果:
END
这篇关于vTable实现多维表格的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!