<template>
<div class="content_body" ref="chartContainer">
</div>
</template>
<script>
import * as echarts from 'echarts'
import { ResizeObserverHelper } from '@/module/util/resizeObserverHelper.js';
const color = ['#6b7585', '#1de9b6', '#40fdce', '#885BD2', '#B6D8F3']
export default {
data () {
return {
chart: null,
observer: null,
}
},
watch: {
},
mounted () {
this.updateChartData()
},
beforeMount () {
if (this.chart) {
this.chart.dispose();
this.chart = null;
}
this.observer && this.observer.disconnect();
},
methods: {
initChart (newData) {
try {
this.chart = echarts.init(this.$refs.chartContainer);
this.updateChartData(newData)
this.observer = new ResizeObserverHelper(this.$refs.chartContainer, (width, height) => {
this.chart && this.chart.resize();
});
} catch (error) {
}
},
updateChartData (newData) {
if (!this.chart) {
this.$nextTick(() => {
this.initChart(newData);
});
return;
}
this.chart.setOption(</script>
<style lang="scss" scoped>
.content_body {
height: 100%;
}
</style>
export class ResizeObserverHelper {
constructor(target, callback, debounceDelay = 200) {
this.target = typeof target === 'string' ? document.querySelector(target) : target;
this.callback = callback;
this.debounceDelay = debounceDelay;
this.debounceTimer = null;
this.resizeObserver = null;
this.init();
}
init() {
if (this.target === window) {
this.handleWindowResize();
return;
}
if (this.target instanceof HTMLElement) {
this.handleElementResize();
return;
}
throw new Error('Invalid target: must be HTMLElement, window, or CSS selector');
}
handleWindowResize() {
const handler = () => {
this.debouncedCallback(window.innerWidth, window.innerHeight);
};
window.addEventListener('resize', handler);
this.disconnect = () => window.removeEventListener('resize', handler);
handler();
}
handleElementResize() {
this.resizeObserver = new ResizeObserver((entries) => {
const { width, height } = entries[0].contentRect;
this.debouncedCallback(width, height);
});
this.resizeObserver.observe(this.target);
this.disconnect = () => this.resizeObserver.disconnect();
}
debouncedCallback = (width, height) => {
clearTimeout(this.debounceTimer);
this.debounceTimer = setTimeout(() => {
this.callback(width, height);
}, this.debounceDelay);
};
disconnect() {
if (this.disconnect) this.disconnect();
clearTimeout(this.debounceTimer);
}
}