Number2 echarts动态获取数据
继续上一篇,结合echarts动态获取数据
官方提供了一个微信与echarts相结合的数据,里面就是简单的各种工具,数据获取没有进行动态绑定,各种搜索资料最后编写了一个动态获取数据的方法
这里以官方示例pie做改造
1.index.js
import * as echarts from '../../ec-canvas/echarts';
const app = getApp();
function setOption(chart,piedata){
var option = {
backgroundColor: "#ffffff",
series: [{
label: {
normal: {
fontSize: 14
}
},
type: 'pie',
center: ['50%', '50%'],
radius: ['20%', '40%'],
data: piedata
}]
};
chart.setOption(option);
return chart;
}
Page({
data: {
ec: {
//onInit: initChart
// 将 lazyLoad 设为 true 后,需要手动初始化图表
lazyLoad: true
}
},
initpie:function(piedata){
let ecComponent = this.selectComponent('#mychart-dom-pie');
ecComponent.init((canvas, width, height, dpr) => {
// 获取组件的 canvas、width、height 后的回调函数
// 在这里初始化图表
const chart = echarts.init(canvas, null, {
width: width,
height: height,
devicePixelRatio: dpr // new
});
//调用设定EChart报表状态的函数,并且把从后端拿到的数据传过去
setOption(chart,piedata);
// 注意这里一定要返回 chart 实例,否则会影响事件处理等
return chart;
});
},
onReady() {
},
onLoad: function (options) {
var piedata = [{
value: 55,
name: '北京'
}, {
value: 20,
name: '武汉'
}, {
value: 10,
name: '杭州'
}, {
value: 20,
name: '广州'
}, {
value: 38,
name: '上海'
}];
this.initpie(piedata);
}
});
2、index.json
{
"usingComponents": {
"ec-canvas": "../../ec-canvas/ec-canvas"
}
}
3、index.wxml
<!--index.wxml-->
<view class="container">
<ec-canvas id="mychart-dom-pie" canvas-id="mychart-pie" ec="{{ ec }}"></ec-canvas>
</view>
4、index.wxss
/**index.wxss**/
ec-canvas {
width: 100%;
height: 100%;
}
注意这里虽然只有ec-canvas的样式设置,但是需要在ec-canvas外面包裹<view>
标签,并设置宽以及高,要不然图表不会显示,就跟jsp引用echarts
代码示例放在https://download.csdn.net/download/dongyang1124/85110432