本文介绍微信小程序中ECharts的数据绑定的一种方法。
在微信小程序中使用ECharts时,官方教程的数据是固定的,并没有提到如何获取数据。
问题描述:
我们把数据放在和图表同一个页面,数据会无法绑定上,和小程序页面的生命周期有关:
data: {
ec: {
onInit: initChart
},
解决方案:
在微信小程序中,我们还有一个可以存储App全局变量的地方:app.js。
我们可以在图表展示的前一个界面,将数据先从服务器获取到,存入app.js的globalData{}:
util.HttpRequst(true, \'YourUrl\', 1, YourCookie, { YourData }, \'GET\', false, function (data) { if (JSON.parse(data)[0].msghead == \'success\') { let dataStr = JSON.parse(data)[0].msgbody; let dataObj = JSON.parse(dataStr); //获取数据 for (var idx in dataObj) { //数据分别存入globalData app.globalData.chartsData.monthList[idx] = dataObj[idx].MONTH; app.globalData.chartsData.totalList[idx] = dataObj[idx].TOTALFARE; app.globalData.chartsData.waterList[idx] = dataObj[idx].WATERFARE; app.globalData.chartsData.electricList[idx] = -dataObj[idx].ELECTRICFARE; } console.log(app.globalData.chartsData); } }); wx.navigateTo({ url: \'/pages/costtrend/costtrend\', })
然后再跳转到图表展示页面时,表格数据绑定更改为globalData{}:
// pages/costtrend/costtrend.js const app = getApp(); import * as echarts from \'../../components/ec-canvas/echarts\'; let chart = null; Page({ /** * 页面的初始数据 */ data: { ec: { onInit: initChart }, }, ... function initChart(canvas, width, height) { var that = this; chart = echarts.init(canvas, null, { width: width, height: height }); canvas.setChart(chart); var option = { color: [\'#37a2da\', \'#32c5e9\', \'#67e0e3\'], tooltip: { trigger: \'axis\', axisPointer: { // 坐标轴指示器,坐标轴触发有效 type: \'shadow\' // 默认为直线,可选为:\'line\' | \'shadow\' } }, legend: { data: [\'总费用\', \'电费\', \'水费\'] }, grid: { left: 20, right: 20, bottom: 15, top: 40, containLabel: true }, xAxis: [ { type: \'value\', axisLine: { lineStyle: { color: \'#999\' } }, axisLabel: { color: \'#666\' } } ], yAxis: [ { type: \'category\', axisTick: { show: false }, data: app.globalData.chartsData.monthList, //数据绑定更改为globalData axisLine: { lineStyle: { color: \'#999\' } }, axisLabel: { color: \'#666\' } } ], series: [ { name: \'总费用\', type: \'bar\', label: { normal: { show: true, } }, data: app.globalData.chartsData.totalList, //数据绑定更改为globalData itemStyle: { // emphasis: { // color: \'#37a2da\' // } } }, { name: \'电费\', type: \'bar\', stack: \'总量\', label: { normal: { show: true, position:\'left\' } }, data: app.globalData.chartsData.electricList, //数据绑定更改为globalData itemStyle: { // emphasis: { // color: \'#32c5e9\' // } } }, { name: \'水费\', type: \'bar\', stack: \'总量\', label: { normal: { show: true, position: \'right\' } }, data: app.globalData.chartsData.waterList, //数据绑定更改为globalData itemStyle: { // emphasis: { // color: \'#67e0e3\' // } } } ] }; chart.setOption(option); return chart; }