对于如何在微信小程序中使用Echarts这里不做过多的介绍(很简单),这里给大家演示一下如何在项目中使用wx.request获取数据并渲染Echarts
index.wxml
<view class="container">
<ec-canvas id="mychart-dom-bar" canvas-id="mychart-bar" ec="{
{ ec }}"></ec-canvas>
</view>
index.js
import * as echarts from '../../ec-canvas/echarts';
// chart为图表实例,记得要声明为全局的
var chart = null
function initChart(canvas, width, height, dpr) {
chart = echarts.init(canvas, null, {
width: width,
height: height,
devicePixelRatio: dpr
});
chart.showLoading() //显示Loading
canvas.setChart(chart);
var option = {
title: {
text: '获取数据中',
left: 'center'
},
};
chart.setOption(option);
return chart;
}
Page({
data: {
ec: {
onInit: initChart
}
},
onLoad() {
},
getData() {
//这里是模拟的数据请求,项目中请使用wx.request替换掉setTimeouot
setTimeout(() => {
chart.hideLoading() //隐藏Loading
chart.setOption({
title: {
text: '获取数据完成',
},
legend: {
data: ['A', 'B', 'C'],
top: 50,
left: 'center',
backgroundColor: 'red',
z: 100
},
grid: {
containLabel: true
},
tooltip: {
show: true,
trigger: 'axis'
},
xAxis: {
type: 'category',
boundaryGap: false,
data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
// show: false
},
yAxis: {
x: 'center',
type: 'value',
splitLine: {
lineStyle: {
type: 'dashed'
}
}
// show: false
},
series: [{
name: 'A',
type: 'line',
smooth: true,
data: [18, 36, 65, 30, 78, 40, 33]
}, {
name: 'B',
type: 'line',
smooth: true,
data: [12, 50, 51, 35, 70, 30, 20]
}, {
name: 'C',
type: 'line',
smooth: true,
data: [10, 30, 31, 50, 40, 20, 10]
}]
})
}, 1000);
},
onReady() {
//获取数据
this.getData()
},
});
index.json
{
"usingComponents": {
"ec-canvas": "../../ec-canvas/ec-canvas"
},
"navigationBarTitleText": "Echarts Example"
}
最终的效果图如下: