本人比较懒,很少写文章,抽空把日常开发的片段发出来让大家交流。废话不多说,上代码。
<template>
<div style="width:100%;height:100%;">
<div :id="id" style="width:100%;height:100%;overflow: hidden;" ></div>
</div>
</template>
<script>
// div监听
var elementResizeDetectorMaker = require("element-resize-detector")
import echarts from 'echarts'
export default {
props: {
option:{
type:Object,
detault:{}
},
params:{
type:Object,
detault:{
isShowLoading:true,
clickEvent:false,
mouseoverEvent:false,
clear:false
}
}
},
data(){
return {
id:'#' + Math.random(),
myChart:null,
ledgend:null,
}
},
watch:{
option:{
handler(val){
if(this.myChart && this.option){
this.createChartDatas();
}else{
this.$nextTick(() => {
this.initChart();
})
}
},
deep:true,
immediate: true,
},
},
methods: {
// 获取导出图片
getChartDataUrl(){
let src = this.myChart.getDataURL({
// 导出的格式,可选 png, jpeg
type: 'png',
// 导出的图片分辨率比例,默认为 1。 11000
pixelRatio: 2
});
this.$emit("getChartDataUrl", src);
},
// 初始化
initChart(){
this.myChart = echarts.init(document.getElementById(this.id));
this.createChartDatas();
this.initEvent();
this.$emit("chartClick",this.myChart)
this.myChart.on('legendselectchanged', (params=>{
console.log(params);
this.ledgend = params.selected
}));
},
initEvent(){
let that = this;
if(this.params.clickEvent){
this.myChart.on('click', function (params) {
console.log(params);
that.$emit("chartClick",params)
});
}
if(this.params.mouseoverEvent){
this.myChart.on('mouseover', function (params) {
console.log(params);
that.$emit("chartMouseover",params)
});
}
},
// 绘制图表
createChartDatas(){
// 清空画布
if(this.params.clear){
this.myChart.clear();
}
if(this.option){
if(this.ledgend){
this.option.legend.selected = this.ledgend
}
this.myChart.setOption(this.option,true);
this.hideLoading();
}
},
updateOption(option){
if(this.myChart){
this.myChart.setOption(this.option,true);
this.hideLoading();
}
},
onWindowResize(){
this.myChart.resize();
},
showLoading(option){
if(this.myChart){
this.myChart.showLoading(option);
}
},
hideLoading(){
if(this.myChart){
this.myChart.hideLoading();
}
}
},
mounted () {
this.$nextTick(() => {
this.initChart();
})
var erd = elementResizeDetectorMaker()
let that = this;
erd.listenTo(document.getElementById(this.id), function (element) {
that.$nextTick(function () {
that.onWindowResize();
})
})
},
beforeDestroy() {
if(this.myChart){
this.myChart.dispose();
}
}
}
</script>
父组件调用
<common-echart v-if="ChartShow" style="width:100%;height: 100%;" :option="ChartOption" :params="{isShowLoading:true,clickEvent:true,mouseoverEvent:false}"></common-echart>
此处的ChartOption就是echart的option对象,丢进去就行