处理监听图表的函数,确保及时移除&生产环境不打印log
This commit is contained in:
@@ -9,7 +9,8 @@ export default {
|
||||
components: {},
|
||||
data() {
|
||||
return {
|
||||
myChart: null // 保存图表实例,方便更新
|
||||
myChart: null, // 保存图表实例,方便更新
|
||||
resizeHandler: null // 窗口resize事件处理器
|
||||
};
|
||||
},
|
||||
props: {
|
||||
@@ -35,6 +36,13 @@ export default {
|
||||
this.$nextTick(() => {
|
||||
this.initChart();
|
||||
});
|
||||
// 注册窗口resize事件,使用稳定的引用以便后续移除
|
||||
this.resizeHandler = () => {
|
||||
if (this.myChart) {
|
||||
this.myChart.resize();
|
||||
}
|
||||
};
|
||||
window.addEventListener('resize', this.resizeHandler);
|
||||
},
|
||||
methods: {
|
||||
initChart() {
|
||||
@@ -45,19 +53,18 @@ export default {
|
||||
}
|
||||
this.myChart = echarts.init(chartDom);
|
||||
this.updateChart(); // 初始化图表数据
|
||||
|
||||
// 窗口缩放适配
|
||||
window.addEventListener('resize', () => {
|
||||
this.myChart && this.myChart.resize();
|
||||
});
|
||||
|
||||
// 组件销毁清理
|
||||
this.$once('hook:destroyed', () => {
|
||||
window.removeEventListener('resize', () => {
|
||||
this.myChart && this.myChart.resize();
|
||||
});
|
||||
this.myChart && this.myChart.dispose();
|
||||
});
|
||||
},
|
||||
beforeDestroy() {
|
||||
// 移除窗口resize事件监听器
|
||||
if (this.resizeHandler) {
|
||||
window.removeEventListener('resize', this.resizeHandler);
|
||||
this.resizeHandler = null;
|
||||
}
|
||||
// 销毁图表,避免内存泄漏
|
||||
if (this.myChart) {
|
||||
this.myChart.dispose();
|
||||
this.myChart = null;
|
||||
}
|
||||
},
|
||||
|
||||
updateChart() {
|
||||
|
||||
Reference in New Issue
Block a user