需求:
通过遍历数据渲染多个echarts图表,需要通过监听包裹echarts图表的div大小实现echarts图表的自适应。要实现以上需求我们可以使用 ResizeObserver。ResizeObserver 提供了一种有效地监测 DOM 元素大小变化的方式。以便使用 ResizeObserver 来监听 newDiv
元素的大小变化并在变化时重新渲染图表:
props.multipleSelection.forEach((element: any,index:any)=> {
const newDiv = document.createElement('div');
newDiv.id='chart'+index
newDiv.style.width="400px"
newDiv.style.height = '300px';
// 添加draggable属性
newDiv.draggable = true;
newDiv.style.backgroundColor="#eee"
newDiv.style.margin="10px 10px";
newDiv.style.flex="1";
const chart=document.getElementById('chart'+index)
const myChart = echarts.init(chart);
chartInstances.push(myChart);
myChart.setOption({
animationDuration:1000,
title: {
text:element.labelName
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'cross',
label: {
backgroundColor: '#6a7985'
}
}
},
xAxis: {
type: 'category',
data: timeLine,
name: "时间"
},
yAxis: {
name: '值',
},
grid: {
right: 140,
},
series: seriesData.value,
})
//仅限于window视口发生变化时
window.addEventListener("resize", function () {
myChart.resize();
});
const ro = new ResizeObserver((entries) => {
myChart.resize();
});
ro.observe(chart!);
});
需要为每个图表元素单独创建一个ResizeObserver。
注意:我遇到一个问题,因为我把mychart设置成了全局变量,导致所有的 ResizeObserver
共享相同的 myChart
实例,最后只监听到最后一个div的变化,其他没有监听到。
所以在每次迭代中创建新的 myChart
实例,确保了每个图表元素都有自己的 ECharts 实例,这样就不会相互影响。
实现效果图: