效果图
应用场景
需要实现数据下钻的,比如年销售额到月销售额,应用场景很多。
html
<template>
<div class="chart">
<div ref="chartEle" id="chart" style="width: 100%; height: 600px; margin: 0 auto;"></div>
<div class="btn-box">
<el-button @click="getChartData('month')">click</el-button>
<el-button @click="reset">reset</el-button>
<el-button @click="prev">prev</el-button>
</div>
</div>
</template>
js
export default {
name: "Chart",
data() {
return {
myChart: null,
status: 2,
month: '01',
date: '2019-01-01'
}
},
mounted() {
this.myChart = this.$echart.init(this.$refs.chartEle);
this.clickChart();
},
methods: {
//渲染图表
renderChart(xData, yData, name) {
let option = {
color: ['#bfccff'],
title: {
text: ''
},
tooltip: {
},
xAxis: {
data: xData,
name: name
},
yAxis: {
name: 'sunlight'
},
series: [{
name: name, //可以当做一个唯一的属性,用来判断当前的图表
type: name == 'h' ? 'line' : 'bar',
smooth: true,
barCategoryGap: '50%',
data: yData,
itemStyle: {
color: new this.$echart.graphic.LinearGradient(
0, 0, 0, 2,
[
{
offset: 0, color: '#C346C2'},
{
offset: 0.5, color: '#F5CBFF'}
])
},
areaStyle: {
}
}]
};
this.myChart.setOption(option);
window.addEventListener('resize', () => {
this.myChart.resize();
});
},
//获取图表数据
getChartData(name) {
const url = '/power/projPower/getAll';
let data = {
'pid': 990,
'status': this.status,
'month': this.month,
'date': this.date
};
this.$ajax.get(url, {
'params': data
}).then(res => {
if (res.code == 200) {
this.renderChart(res.data.times, res.data.number, name);
}
})
},
//图表点击下钻
clickChart() {
this.myChart.on('click', params => {
switch (params.seriesName) {
case 'month':
this.status = 1;
this.month = params.name.length < 2 ? '0'.concat(params.name) : params.name;
this.getChartData('day');
break;
case 'day':
this.status = 0;
this.date = params.name.length < 2 ? '0'.concat(params.name) : params.name;
this.date = '2019-' + this.month + '-' + this.date;
this.getChartData('h');
break;
default:
break;
}
})
},
//还原为最开始的数据
reset() {
this.status = 2;
this.getChartData('month');
},
//返回上一步图表数据
prev() {
switch (this.status) {
case 1:
this.status = 2;
this.getChartData('month');
break;
case 0:
this.status = 1;
this.getChartData('day');
break;
default:
break;
}
}
}
}
实现原理
一、echarts实例对象独立声明且只有一次。
二、图表click事件写在渲染函数外面。
在我实现的过程中,降低耦合度很重要,代码能拆分的越简单越好,可以避免很多问题。