Vue-cli中使用echarts
2019-12-03 本文已影响0人
Gino_Li
npm包选择:
推荐使用echarts,不推荐使用vue-echarts(更新慢等问题)。
npm i echarts
使用方式:
- 推荐使用vue提供的mixin混入
mixin适合存放一些可复用性的方法和变量,以及统一管理同类型的控件。 - 不推荐在mixin中写钩子函数(created,mounted等),否则一个页面中mixin多个的话,钩子函数会触发多次。
- 具体:https://cn.vuejs.org/v2/guide/mixins.html
步骤:
一.封装(echartsMixin.js )
1.引入echarts
import echarts from 'echarts';
2.echarts配置option,以柱状图为例
注意:代码必须写在computed中,写在data中的话echarts不会响应数据改变,因为mixin实例比引入的组件早,所以会先拿到data里的初始数据
computed: {
option() {
return {
tooltip: {
trigger: 'axis',
axisPointer: { // 坐标轴指示器,坐标轴触发有效
type: 'shadow' // 默认为直线,可选为:'line' | 'shadow'
}
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: [{
type: 'category',
data: this.timeCompareAxis,
axisTick: {
alignWithLabel: true
},
axisLabel:{
'interval':0,
rotate:20
},
}],
yAxis: [{
type: 'value',
}],
series: [{
type: 'bar',
barWidth: '60%',
data: this.timeCompareChartData,
label: {
normal: {
show: true,
position: 'top'
}
}
}]
}
}
}
3.变量
data() {
return {
timeCompareChartData: [],
timeCompareAxis: []
}
}
4.写一个实例化echarts的方法
methods: {
drawChart(options, _id, isBar) {
let _this = this;
if (document.getElementById(_id)) {
let chartInstance = echarts.init(document.getElementById(_id));
chartInstance.setOption(options)
chartInstance.resize();
//根据窗口的大小变动图表(自适应)
window.addEventListener('resize', () => {
chartInstance.resize();
})
}
}
}
二.调用(app.vue)
结构样式
<div class="chartbox">
<div id="chart1" class="echarts"></div>
</div>
.chartbox {
//必须外面套一个盒子给宽高
width: 100%;
height: 200px;
.echarts {
width: 100%;
height: 100%;
}
}
import echartsMixin from "@/mixins/echartsMixin"
export default {
mixins: [echartsMixin],
methods: {
getHandleTotal(params) {
//请求数据
this.$get(XXX,params).then(res => {
//数据处理
res.forEach(val => {
this.timeCompareChartData.push(val.data);
timeCompareAxis.push(val.axis);
})
}).then(()=>{
//实例化echarts,必须异步执行
this.drawChart(this.option, "chart1", true);
});
}
}
大功告成
- 如果需要使用折线图,地图等,只需在echartMixin中增加配置option就可以了,然后重复第二步调用的方法。
- 这样写的好处就是能够用一个文件统一管理项目中所有echarts图表,维护只需找到对应的option就可以修改了。