The adaptive problem of multiple echart charts on one page, the personal test is effective! ! ! (The author is the Vue2 project)

According to echars official website, the adaptive usage of a single echar graph is as follows

window.onresize = () => {
    this.myChart.resize();
};

There is a problem with the above method, that is, there are multiple echart images on a page, and only the last echart image to be rendered will be adapted when adaptive.

This leads to the following way of writing, replacing the abbreviated onresize with addEventListener.

Add event listeners Remember to remove event listeners when leaving to avoid memory leaks!

To remove an event listener, the event's function needs to use a named function!

data() {
    return {
        myChart:''
    }
}
mounted() {
    this.loadChart();
}
beforeDestroy() {
    // 离开页面必须进行移除,否则会造成内存泄漏,导致卡顿
    window.removeEventListener('resize', this.resizeFn);
}
methods: {
    // 渲染echart图
    loadChart() {
        // 获取绘图的节点,并初始化
        this.myChart = this.$echarts.init(document.getElementById('chart'));
        // 自己项目echart图的配置
        const chartOption = {...} 
        this.myChart.setOption(chartOption);
        setTimeout(() => {
            window.addEventListener('resize', this.resizeFn);
        }, 100)
    }
    // 使用具名自适应函数,用于离开页面时可以卸载监听事件使用
    resizeFn() {
        return this.myChart.resize();
    }
}

We can open Element -> EventListeners -> click the refresh icon in the figure below in the console.

Look at our current event listeners, each resize corresponds to a different echart graph we bind to the event listener.

When we need to verify whether the event listener is removed when we leave the page, we can click the refresh icon marked in the figure below after jumping to the page to see whether the event is removed to ensure that the memory is not leaked.

I hope it can help those who need it, and please correct me if there are mistakes.

Guess you like

Origin blog.csdn.net/weixin_42627850/article/details/128903921