需求背景:
小程序中页面,饼图的legend需要支持用户点击出现弹出框;官网上点击legend时只支持选中/取消当前对应的模块
解决方案:监听legendSelectchanged事件,执行legend被点击后立即被选中,然后再写其他自定义业务代码
onLoad() {
this.initChart()
}
// 初始化chart
initChart(type) {
const self = this
const option = {...} // 设置数据及配置项option
this.chartComponnet = this.selectComponent('#mychart-dom-pie'); // 去获取echarts 这里的id就是echarts的id
this.chartComponnet.init((canvas, width, height, dpr) => {
const foodChart = echarts.init(canvas, null, { // echarts会继承父元素的宽高
width: width,
height: height,
devicePixelRatio: dpr
});
foodChart.setOption(option); // 这一步是给echarts 设置数据及配置项option
//重要代码 点击legend start
foodChart.on('legendSelectchanged', function (params) {
console.log('legend被点击')
foodChart.setOption({
legend: {
selected: {
[params.name]: true // 此步为了点击legend后重新被选中
}
}
})
// 出现弹窗
self.setData({
showFood: true
})
})
//重要代码 点击legend end
return foodChart;
});
}