const DESIGN_WIDTH = 1920; export function px2echarts(px) { const scale = window.innerWidth / DESIGN_WIDTH; return Math.round(px * scale); } export default { data() { return { $_chart: null, $_resizeObserver: null // 替换原来的 resizeHandler }; }, mounted() { // 确保 DOM 完全渲染后再进行监听 this.$nextTick(() => { this.$_initResizeObserver(); }); }, beforeDestroy() { this.$_destroyResizeObserver(); if (this.$_chart) { this.$_chart.dispose(); this.$_chart = null; } }, methods: { $_initResizeObserver() { // 【智能挂载点】:优先寻找 ref="chartRef" 的专属图表容器,如果没有,则退而求其次监听整个组件根节点 ($el) const targetDom = this.$refs.chartRef || this.$el; // 确保取到的是有效的 DOM 元素 if (!targetDom || targetDom.nodeType !== 1) return; let timer = null; this.$_resizeObserver = new ResizeObserver(() => { // 使用防抖 (Debounce) 避免拖拽弹窗时触发过于频繁导致页面卡顿 if (timer) clearTimeout(timer); timer = setTimeout(() => { // 结合 requestAnimationFrame,在浏览器下一次重绘前执行,动画更丝滑 // 并且能有效避免 "ResizeObserver loop limit exceeded" 这种控制台红字报错 requestAnimationFrame(() => { if (this.$_chart) { // 1. 强制 ECharts 重绘画布物理大小 this.$_chart.resize(); // 2. 如果组件内部写了 updateChart 方法,自动触发它! if (typeof this.updateChart === 'function') { this.updateChart(); } } }); }, 50); // 50ms 是兼顾拖拽流畅度和 CPU 性能的黄金时间 }); // 开始监听 this.$_resizeObserver.observe(targetDom); }, $_destroyResizeObserver() { if (this.$_resizeObserver) { this.$_resizeObserver.disconnect(); // 停止监听,释放内存 this.$_resizeObserver = null; } } } };