/**
* Wrapper on top of echart vue components
*
* @example
* {
* mixins: [
echartMixin((vm) => vm.$refs.chart, {
optionsHandler: createEchartInstanceOptions,
renderOnMounted: true,
}),
],
watch:{
value(){
this.renderChart();
}
}
* }
* @param {Object} echarts Echarts core singleton (i.e import * as echarts from 'echarts/core'; echarts.use([GaugeChart, CanvasRenderer]))
* @param {Object} domElement Dom element used to render the chart
* @param {Function} options.optionsHandler Handler to compute echart options
*/
const echartMixin = (echarts, domElement, options = {}) => {
return {
data() {
return {}
},
mounted() {
let computedDomElement = domElement
if (typeof domElement === 'function') {
computedDomElement = domElement.apply(this, [this])
}
if (!this.chartInstance) {
this.chartInstance = echarts.init(computedDomElement)
window.addEventListener('resize', this.onWindowResize)
window.addEventListener('orientationchange', this.onWindowResize)
}
if (options.optionsHandler) {
this.setUpdateChartInstanceOptionsHandler(options.optionsHandler)
}
if (options.renderOnMounted) {
this.renderChart()
}
},
methods: {
onWindowResize() {
if (!this._isDestroyed && !!this.chartInstance) {
this.chartInstance.resize({
width: 'auto',
height: 'auto',
})
}
},
setUpdateChartInstanceOptionsHandler(cb) {
this.updateChartInstanceOptionsHandler = cb
},
updateChartInstanceOptions() {
if (this.updateChartInstanceOptionsHandler) {
this.chartInstanceOptions =
this.updateChartInstanceOptionsHandler.apply(this, [this])
} else {
console.warn(
'echart-mixin',
'call setUpdateChartInstanceOptionsHandler to setup an options handler'
)
this.chartInstanceOptions = {}
}
},
renderChart() {
if (this.chartInstance) {
this.updateChartInstanceOptions()
let options = this.chartInstanceOptions
this.$nextTick(() => {
setTimeout(() => {
this.chartInstance.setOption(options)
}, 100)
})
}
},
},
}
}
export default echartMixin
Source