在微信小程序中,常常需要獲取后臺(tái)的數(shù)據(jù),對(duì)數(shù)據(jù)進(jìn)行相對(duì)應(yīng)的處理之后,再結(jié)合該數(shù)據(jù)對(duì)圖表進(jìn)行渲染。
但是,在官方給出的ECharts的微信小程序版本的示例中,是把配置函數(shù)寫在了page之外,那么我們要如何獲取后臺(tái)傳來的數(shù)據(jù)對(duì)圖表進(jìn)行渲染呢?
防止有的人不了解如何在微信小程序中使用echarts,我們先從圖表組件的引入開始說起:
1.下載
首先我們需要下載echarts的組件,放置到微信小程序當(dāng)中,作為頁面的子組件來使用。
ecomfe/echarts-for-weixin
把該文件下載下來之后,把文件中ec-canvas的文件夾拷貝到小程序項(xiàng)目中的組件文件夾下。
2.引入組件
下載了echarts組件之后,把需要使用echarts的js頁面(index頁面下)當(dāng)中引入該組件:
(1)
import * as echarts from '../../../../../ec-canvas/echarts';
(2) 在index.html 引入echarts組件 :
<view class='content'>
<ec-canvas id="my-canvas" canvas-id="mycharts-line" ec="{{ec}}"></ec-canvas>
</view>
注意!在ec-canvas的組件上一定要加一個(gè)view并且給view一個(gè)寬高,因?yàn)閑c-vanvas的寬高是百分比的,所以一定要給外層的view一個(gè)寬高,這樣才能正確的渲染出來。除此之外,需要給這個(gè)ec-canvas的組件一個(gè)id名。
這樣,就能在頁面中引用該組件了
3.編寫圖表配置
getCwData(){
return {
color: ["#36de95", "#f25259", "#fbbb56", "#f7d756", "#383bc6","#57b8f5"],
grid: {
left: '3%',
right: '5%'
},
backgroundColor: '#fff',
series: [
{
type: 'pie',
center: ['50%', '50%'],
radius: '45%',
data: [{name:'類型1', value: 10}, {name:'類型2', value: 100}],
// data: _this.data.存儲(chǔ)數(shù)據(jù)的變量名,
label: {
normal: {
textStyle: {
color: '#000',
fontSize: 14
},
padding: [0, -25],
formatter: function (params) {
var personnelPercent = Math.round(params.percent);
var result = params.name + personnelPercent + "% \n\n";
return result;
},
rich: {}
}
},
labelLine: {
normal: {
length: 20,
length2: 40
}
},
}
]
};
}
4.在編寫完圖表配置之后,在頁面page中的data中配置初始化,如何初始化?
在js頁面的data中給該組件一個(gè)懶加載
ec: {
lazyLoad: true,
},
5.在js文件中的onload函數(shù)中,獲取到該組件對(duì)象
this.emotionsEcharts = this.selectComponent('#my-canvas');
6.定義一個(gè)對(duì)圖表進(jìn)行初始化的函數(shù)
init_echarts(el, fn) {
el.init((canvas, width, height) => {
// 初始化圖表
const Chart = echarts.init(canvas, null, {
width: width,
height: height
});
Chart.setOption(fn());
// 注意這里一定要返回 chart 實(shí)例,否則會(huì)影響事件處理等
return Chart;
});
},
7.在獲取到后臺(tái)數(shù)據(jù)之后,就可以對(duì)該圖表進(jìn)行渲染
(前面是接口數(shù)據(jù)的處理,把圖表需要的數(shù)據(jù)存到data下的變量里)
_this.init_echarts(_this.emotionsEcharts , _this.getCwData);
這樣,就是一個(gè)完整的在小程序中異步加載echarts圖表。
(如有任何不對(duì)的地方,請(qǐng)?zhí)岢鲋刚u(píng)?。。。?/p>