我子组件数组遍历循环绘制多个相同的echart
图形,在子组件的 mounted 中使用 resize,结果只对页面最后一个图表生效。
原因: 数组遍历会生成多个实例 echart,resize 只对一个且最后一个实例生效,无法对多个实例进行 resize。
错误写法:在子组件中使用的
window.onresize = function() {
myChart.resize();
};
正确写法:在store中定义变量数组myChartAll,子组件将创建的每个echart实例存入store中,父组件遍历myChartAll数组进行resize就ok
子组件
子组件代码:
let chartDom = document.getElementById(item.chartId);
this.myChart = echarts.init(chartDom);
this.$store.state.myChartAll.push(this.myChart);
父组件
父组件代码:
let echartAll = this.$store.state.myChartAll;
window.onresize = function () {
for (let i = 0; i < echartAll.length; i++) {
echartAll[i].resize();
}
};
效果图: