简体   繁体   中英

how to use Intersection Observer API immediately?

I use Intersection Observer API to know when the element is in the viewport or not, which works fine.

How to use Intersection Observer API to know if the element is in the viewport without using callback ?

Something like:

 let options = {
   root: ..
   rootMargin: '0px',
   threshold: 1.0
  }

  let observer = new IntersectionObserver(callback, options);

  const status = observer.isInViewport(); // <------- this what I looking for or something similar. not callback.

its better to be in mounted lifecycle hook because you are using refs, and that means onMounted in composition api. but the is in your callback and here it is:

    const ready = ref(false);
    const myRef = ref(null);

   onMounted(() => {
  const vm = getCurrentInstance();
  let options = {
   root: vm.$refs.myRef
   rootMargin: '0px',
   threshold: 1.0
  }

   let observer = new IntersectionObserver(([entry]) => {
      if (entry && entry.isIntersecting) {
        ready.value = true;
      }
    }, options);
     observer.observe(myRef.value)
 })

  return { ready, myRef }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM