javascript - vue.js 中的 Intersection Observer 问题

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

这是我第一次使用 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>

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

最佳答案

您已更改 defaultoptions从:

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

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

但是如果我们查看 lib.dom.d.ts ,这是 IntersectionObserver 选项对象的接口(interface):
interface IntersectionObserverInit {
  root?: Element | null;
  rootMargin?: string;
  threshold?: number | number[];
}

rootnullundefined , IntersectionObserver默认为视口(viewport)元素。

所以改回null它会起作用。

关于javascript - vue.js 中的 Intersection Observer 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61578205/

相关文章:

laravel - 如何将 cookie 从后端(laravel)发送到前端?

vue.js - 从 main.js 调用 new Vue() V/s 从每个组件调用之间的区别

dom - 使用 Tether 在 Vue 2.2.1 中操作 DOM 会导致错误。有正确的方法吗?

vue.js - Vue 计算 setter 不适用于复选框?

vue.js - 在自定义组件上使用时 v-model 和 .sync 有什么区别

javascript - 如何在 HTML 中正确调用 JS 函数?

javascript - 在 p5.js 中如何将光标替换为圆圈而不是将其绘制到 Canvas 上?

javascript - 无论如何,我要在 jsoncschema 中定义一个字典?

vue.js - 为什么我的 vuetify 对话框隐藏在这个邪恶的覆盖层后面?

javascript - 使用ajax时如何将id从js传递到rails?