导语:my-f2组件二次封装,用来批量生成条形图(业务需要)
1:组件
f2Interval.axml
<f2 onInit="onInitChart"></f2>
f2Interval.js
// chartList 存放chart实例:由于是批量生成图表,所以每个图表的chart实例不能相同
let chartList = {}, _global;
Component({
mixins: [],
data: {},
props: {
data: [], // 图表数据
id: null, // 图表id
},
didMount() {
},
didUpdate(prevProps, prevData) {
// 数据变化时更新
const { id } = this.props
// 更新时其实是做了重绘,直接用changeData(data)出问题,所以用了最笨的方法
this.updataChart(this.props.data, chartList[`chart${id}`])
},
didUnmount() { },
methods: {
updataChart(data, chart) {
chart.clear(); // 清理所有
chart.source(data); // 加载新数据
chart.interval().position('NodeName*count').size(15);
chart.coord({
transposed: true
});
// 设置提示
chart.tooltip({
showItemMarker: false,
onShow: function onShow(ev) {
const items = ev.items;
items[0].name = null;
items[0].name = items[0].title;
items[0].value = items[0].value;
}
});
// 设置轴线
chart.axis('NodeName', {
line: null,
grid: _global._defaultAxis.grid,
label: function label(text, index, total) {
var textCfg = {};
textCfg.textAlign = 'right';
textCfg.text = text.length > 9 ? `${text.slice(0, 9)}\n${text.slice(9)}` : text;
return textCfg;
}
});
data.map(function (obj) {
chart.guide().text({
position: [obj.NodeName, obj.count],
content: obj.count,
style: {
textAlign: 'start'
},
offsetX: 0,
});
});
chart.render();
},
// 初始化chart
onInitChart(F2, config) {
const chart = new F2.Chart(config);
const Global = F2.Global;
const { data, id } = this.props
chartList[`chart${id}`] = chart
_global = Global
this.updataChart(data, chart)
// 注意:需要把chart return 出来
return chart;
},
},
});
f2Interval.json
{
"component": true,
"usingComponents": {
"f2": "@antv/my-f2"
}
}
2:页面使用
f2Interval.axml
<view a:for="{{tabs}}" key="{{index}}">
<f2-interval
a:if="{{item.data.length>0}}"
data="{{item.data}}"
id="{{item.id}}"
></f2-interval>
</view>
<button type="primary" onTap="handleRefresh">刷新</button>
f2Interval.js
Page({
data: {
tabs: [
{
id: 1001, // id:设置成后台数据给定的id值,方便与后台返回的数据进行匹配,插入data
title: 'aaa', // 图表标题
data: [], // 图表数据:从后台获取的数据赋值
},
{
id: 1002, // id:设置成后台数据给定的id值,方便与后台返回的数据进行匹配,插入data
title: 'bbb', // 图表标题
data: [], // 图表数据:从后台获取的数据赋值
},
],
},
onLoad() {
this.getData()
},
getData() {
// 模拟后台返回数据
const data = {
1001: [
{
NodeId: 1,
NodeName: 'a',
count: Math.round(Math.random() * 100) // 设置成(1-100)随机数方便模拟变化的数据
},
{
NodeId: 2,
NodeName: 'b',
count: Math.round(Math.random() * 100)
},
{
NodeId: 3,
NodeName: 'c',
count: Math.round(Math.random() * 100)
},
],
1002: [
{
NodeId: 1,
NodeName: 'e',
count: Math.round(Math.random() * 100)
},
{
NodeId: 2,
NodeName: 'f',
count: Math.round(Math.random() * 100)
},
{
NodeId: 3,
NodeName: 'g',
count: Math.round(Math.random() * 100)
},
]
}
const tabs = this.data.tabs
tabs.forEach((el, index) => {
this.setData({
[`tabs[${index}].data`]: data[el.id]
})
})
},
// 刷新
handleRefresh() {
this.getData()
}
});
f2Interval.json
{
"defaultTitle": "批量生成条形图",
"usingComponents": {
"f2-interval": "/components/f2Interval/f2Interval"
}
}