效果
引入ECharts
参见 https://github.com/ecomfe/echarts-for-weixin
目录
源码
pages/index/index.json
{
"usingComponents": {
"ec-canvas": "../../ec-canvas/ec-canvas"
}
}
pages/index/index.wxml
<view class="container">
<button bindtap="chartInit" size="mini" type="primary">请求数据加载图表</button>
<button bindtap="chartReLoad" size="mini" type="primary">修改数据重载图表</button>
<button bindtap="chartClear" size="mini" type="primary">清除图表数据</button>
<button bindtap="chartShow" size="mini" type="primary">显示图表(使用保存起来的数据的副本)</button>
<button bindtap="chartDispose" size="mini" type="primary">释放图表</button>
<view class="chart" hidden="{{ !isShow }}">
<ec-canvas id="my-chart" canvas-id="mychart-bar" ec="{{ ec }}"></ec-canvas>
</view>
<button bindtap="bindToggle" size="mini" type="primary">切换显示隐藏 {{isShow}}</button>
</view>
pages/index/index.wxss
button{
display: block!important;
margin: 10rpx;
}
.chart {
display: block;
width: 100%;
height: 500rpx;
background-color: #b9b8b8;
}
ec-canvas{
display: block;
width: 100%;
height: 500rpx;
}
pages/index/index.js
import * as echarts from '../../ec-canvas/echarts';
Page({
ecComponent: null,
chart: null,
onLoad() {
const that = this;
that.ecComponent = that.selectComponent('#my-chart');
},
data: {
isShow: false,
ec: {
lazyLoad: true
},
option: {
grid: {
left: 20,
right: 40,
bottom: 15,
top: 40,
containLabel: true
},
xAxis: {
type: 'value',
},
yAxis: {
type: 'category',
data: [],
},
series: [{
type: 'bar',
data: [],
}]
},
},
chartInit() {
const that = this;
if (!that.ecComponent) return wx.showToast({
icon: "error",
title: '请初始化组件',
});
that.ecComponent.init((canvas, width, height, dpr) => {
const chart = echarts.init(canvas, null, {
width: width,
height: height,
devicePixelRatio: dpr
});
setTimeout(() => {
that.data.option.yAxis.data = ['汽车之家', '今日头条', '百度贴吧', '一点资讯', '微信', '微博', '知乎'];
that.data.option.series[0].data = [300, 270, 340, 344, 300, 320, 310];
let option = JSON.parse(JSON.stringify(that.data.option));
chart.setOption(option);
}, 1000)
that.chart = chart;
console.log(chart);
return chart;
});
},
chartReLoad() {
const that = this;
if (that.chart) {
that.data.option.yAxis.data = ['汽车之家', '今日头条', '百度贴吧'];
that.data.option.series[0].data = [300, 270, 340];
let option = JSON.parse(JSON.stringify(that.data.option));
that.chart.setOption(option);
};
},
chartClear() {
const that = this;
if (that.chart) that.chart.clear();
},
chartShow(){
const that = this;
if (that.chart){
let option = JSON.parse(JSON.stringify(that.data.option));
that.chart.setOption(option);
}
},
chartDispose() {
const that = this;
if (that.chart) that.chart.dispose();
},
bindToggle(e){
const that = this;
that.setData({
isShow: !that.data.isShow
})
if(that.data.isShow){
that.chartInit();
}
}
});
|