封装Echarts组件,实现窗口大小改变自适应,监听图表渲染结束事件
<template>
<div class="chart" :ref="ref">
</div>
</template>
<script>
import initEcharts from 'ecarts'
export default {
name: 'Echart',
props: {
options: {
type: Object,
default() {
return {}
}
},
indexSign:{
type: Number,
default: -1
},
finished: {
type: Boolean,
default: false
},
ref: {
type: String,
default: 'chart'
}
},
data() {
return {
chart: null
}
},
watch: {
options: {
immediate: true,
handler(val) {
if (this.chart && this.refs.chart) {
this.chart.setOption(val || {}, true)
} else {
initEcharts().then(echarts => {
this.$nextTick(() => {
this.chart = echarts.init(this.$refs.charts)
this.chart.setOption(val || {}, true)
window.addEventListener('resize', () => {
this.chart.resize()
})
if (this.finished && this.indexSign !== -1) {
const promise = new Promise((resolve, reject) => {
this.chart.on('finished', ()=> {
resolve()
})
})
promise.then(() => {
this.$emit('finishedHandle', this.chart, this.indexSign)
})
}
this.chart.off('click')
this.chart.on('click', (params) => {
this.$emit('getParams', params)
params.event.event.stopPropagation()
})
})
})
}
}
}
},
beforeDestroy() {
this.chart.clear()
this.chart.dispose()
},
}
</script>