Tencent / kbone

一个致力于微信小程序和 Web 端同构的解决方案
Other
4.78k stars 454 forks source link

使用window.$$createIntersectionObserver()页面报错异常错误 #472

Closed 1026203093 closed 10 months ago

1026203093 commented 10 months ago

场景如下: A页面中循环显示了一个组件B ,组件B是一个根据window.$$createIntersectionObserver()来懒加载图片,从小程序首页点击Icon进入A页面,页面的所有图片都能正常加载,没有任何报错。但是从A页面返回到首页,就会报错一个异常,不像是业务代码抛出的,不好定位。我感觉是因为IntersectionObserver导致的,但我在组件销毁前以及onhide。onunload都回调中都关闭的IntersectionObserver,麻烦看下这个报错是什么导致的。 组件B代码如下:

<template>
  <div class="myLazy_image">
    <div v-if="item.url != item.dataUrl" class="lazy_img_empty">
      <img
        style="opacity: 0;"
        :src="item.url"
        :data-url="item.dataUrl"
        class="img_none"
        :class="'lazyImage_item' + item.id"
        @load="handlerLoad"
      />
      <van-loading type="spinner" />
    </div>
    <img v-else :src="item.url" :data-url="item.dataUrl" />
  </div>
</template>

<script>
export default {
  name: "LazyImage",
  props: {
    imageInfo: Object,
    lazyLoadBottom: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      observer: null,
      item: {}
    };
  },

  mounted() {
    this.handler();
    window.addEventListener("wxhide", () => {
      if (this.observer) {
        this.clareOb();
      }
    });
    window.addEventListener("wxunload", () => {
      if (this.observer) {
        this.clareOb();
      }
    });
  },

  beforeDestroy() {
    if (this.observer) {
      this.observer.disconnect();
      this.observer = null;
    }
  },
  methods: {
    handlerLoad() {
      this.createObserver();
    },

    handler() {
      if (this.imageInfo?.url) {
        const iamgeInfo = JSON.parse(JSON.stringify(this.imageInfo));
        this.item = iamgeInfo;
      }
    },

    clareOb() {
      this.observer.disconnect();
      this.observer = null;
    },

    async createObserver() {
      let _this = this;
      let ob = window.$$createIntersectionObserver();
      ob.relativeToViewport({ bottom: this.lazyLoadBottom }).observe(
        `.h5-body >>> .lazyImage_item${_this.item.id}`,
        res => {
          const { intersectionRatio } = res;
          if (intersectionRatio > 0)
            if (_this.item.url === _this.item.dataUrl) return;
          _this.item.url = this.item.dataUrl;
          _this.observer = ob;
          _this.clareOb();
        }
      );
    }
  }
};
</script>

image