【问题标题】:Problem with Intersection Observer in vue.jsvue.js 中的 Intersection Observer 问题
【发布时间】:2020-05-03 16:47:55
【问题描述】:

这是我第一次使用 IntersectionObserver,我关注了这个文档https://www.netguru.com/codestories/infinite-scroll-with-vue.js-and-intersection-observer .但是因为这个错误我被阻止了

[Vue warn]: Error in mounted hook: "TypeError: Failed to construct 'IntersectionObserver': The provided value is not of type '(Element or Document)'"

这是我的触发器组件

<template>
  <span ref='trigger'></span>
</template>

<script>
export default {
  props:{
    options:{
      type: Object,
      default: () => ({
        root: 0,
        threshold: "0",
      })
    }
  },
  data(){
    return{
      observer : null
    }
  },
  mounted(){
    this.observer = new IntersectionObserver( entries => {
      this.handleIntersect(entries[0]);
    }, this.options);

    this.observer.observe(this.$refs.trigger);
  },
  destroyed(){
    this.observer.disconnect();
  },
  methods:{
    handleIntersect(entry){
      if (entry.isIntersecting) this.$emit("triggerIntersected");
    }
  }
}
</script>

我该如何解决这个问题?(谢谢)

【问题讨论】:

  • 您使用的是哪个浏览器和版本?
  • 谷歌浏览器 81.0.4044.129
  • 您是否在 created 生命周期方法中尝试过此操作,而不是 mounted
  • 是的,同样的错误
  • 您的 IntersectionObserver 似乎未定义或未正确导入。

标签: javascript vue.js vue-component intersection-observer


【解决方案1】:

您已将 defaultoptions 更改为:

default: () => {
  return {
    root: null,
    threshold: "0"
  };
}

到:

default: () => ({
  root: 0,
  threshold: "0"
})

但是如果我们查看lib.dom.d.ts,这里是 IntersectionObserver 选项对象的接口:

interface IntersectionObserverInit {
  root?: Element | null;
  rootMargin?: string;
  threshold?: number | number[];
}

rootnullundefined 时,IntersectionObserver 默认为视口元素。

所以把它改回null就可以了。

【讨论】:

  • 您正尝试像数组一样遍历 promise 的响应,但它是 undefined。我需要更多信息来告诉你更多。你能创建一个minimal reproducible example吗?我建议codeandbox.io。顺便说一句,如果你错过了,那篇文章的作者链接了一个demo,你可以从中获得灵感。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-27
  • 1970-01-01
  • 2022-06-04
  • 1970-01-01
相关资源
最近更新 更多