微信小程序版本:2.8.1
wx-f2 版本:27 Aug 2020
数据库:微信云开发
刚开始入手小程序的时候,需要做一些图表,去对比了很多不同的小程序开源图表,还是觉得F2看着最舒服,只是F2的文档不够完善,让人头大。
官方文档给出的F2加载示例是直接使用了现成数据,但实际上我们在运行小程序过程中,经常需要先从数据库里查询数据,再加载图表,这里就涉及到异步加载的问题。
那么具体怎么解决呢,我这里结合微信云开发为例:
- 首先在js文件的data里设置
data: {
showRoseChart:false, //先设置图表不显示
roseChart:{
onInit: () => {} //这一步很重要
}
},
然后定义图表配置(这个参考F2官方文档配置就行)
roseChartConf(F2, config, data) {
const chart = new F2.Chart(config);
chart.source(data);
chart.coord('polar');
chart.legend({
position: 'right'
});
chart.axis(false);
chart.interval().position('_id*length').color('_id').style({
lineWidth: 1,
stroke: '#fff'
});
chart.render();
return chart;
},
再从云数据库里加载数据,在数据加载完成以后,接着加载图表配置
aggTags1yFuc() {
wx.cloud.callFunction({ //调用云函数加载数据
name: 'aggTags',
data: {
openid:app.globalData.openid,
date: this.pastYears(1)
},
})
.then(res => {
console.log("最近一年时间数据",res.result)
this.setData({
roseChart: (F2, config) => this.roseChartConf(F2, config, res.result), //数据加载成功,开始加载F2图表
}),
this.setData({
showRoseChart: true //显示图表
})
})
.catch(console.error)
},
- 记得在json文件中引入组件
{
"usingComponents": {
"f2": "@antv/wx-f2"
}
}
- wxml文件布局
<view class="margin-l padding-xl bg-white radius shadow-lg">
<view class="td"> 最近一年时间分布</view>
<view wx:if="{{showRoseChart}}" class="container">
<f2 class="f2-chart" onInit="{{roseChart}}" />
</view>
</view>
- 在wxss里加入字体及卡片格式的设置
.td {
display: flex;
align-items: center;
justify-content: center;
font-size: 30rpx;
color: black;
}
.f2-chart {
width: 100%;
height: 500rpx;
}
.container{
display: flex;
flex-direction: row;
align-items: flex-end;
flex-wrap: wrap;
}
给大家看一下从云函数里调用生成的数据
还有最后的展示效果
有问题欢迎评论或私信~
此处是 微信小程序F2图表
官方 GitHub链接:https://github.com/antvis/wx-f2