解决echarts报错:Uncaught TypeError: Cannot read property ‘getBoundingClientRect‘ of null at VueComponent

1.需求:vue 移动端的echarts点击图表外部隐藏tooltip

methods:{
    //监听鼠标点击的位置,清除tooltip
    handleChartClick(e) {
      // 判断点击的位置是否在图表上

      const { left, top, width, height } = document
        .getElementById(this.id)
        .getBoundingClientRect();
      const x = e.clientX;
      const y = e.clientY;
      if (x < left || x > left + width || y < top || y > top + height) {
        // 隐藏tooltip
        this.myChart.dispatchAction({ type: "hideTip" });
      }
    },
},
 

2. 在mouted里面监听点击事件,在beforeDestory移除事件

mounted() {
    // 监听点击事件隐藏tooltip
    document.addEventListener("click", this.handleChartClick, true);
  },
  beforeDestroy() {
    // 解绑点击事件
    document.removeEventListener("click", this.handleChartClick, true);
  },
  

好家伙报错了,并且是跳到下一页点击页面之后,才会报错:

Uncaught TypeError: Cannot read property 'getBoundingClientRect' of null at VueComponent.handleChartClick;

搜了一圈都没找到解决方法,然后看到关键字段:VueComponent,打开谷歌调试工具,发现组件没有销毁,处在inactive(未激活)状态,才想起写了keepAlive缓存页面。。。TT

3. 所以需要在deactivated未激活状态移除点击事件:

 deactivated(){ 
    //因为组件缓存,所以也要解绑点击事件
    document.removeEventListener("click", this.handleChartClick, true);
  }

猜你喜欢

转载自blog.csdn.net/CSSAJBQ_/article/details/133386565