Use IntersectionObserver to realize the function of loading elements at the bottom

Use Intersection Observer to realize the function of loading elements at the bottom

In modern web development, we often need to implement some functions related to the visibility and cross state of elements. In the past, we usually use methods such as scroll events or timers to detect the visibility of elements, but these methods are often not efficient and accurate enough. Fortunately, modern browsers provide a powerful API, the Intersection Observer (cross observer), which can help us better monitor the intersection state between elements and windows.

What is Intersection Observer?

Intersection Observer is an API for asynchronously monitoring the intersection state between a target element and its ancestor elements or viewports. It provides an efficient way to detect whether an element is visible or intersects the viewport, and triggers a callback function when the intersection occurs. With Intersection Observer, we can easily implement some common functions, such as lazy loading images, infinite scroll loading and element visibility detection.

Example usage of Intersection Observer

Let's take a common requirement as an example to show how to use Intersection Observer to realize the function of loading elements at the bottom in the Vue development environment.

<template>
  <div>
    <ul>
      <li v-for="item in items" :key="item.id">{
   
   { item.name }}</li>
    </ul>
    <div ref="observerElement"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';

const items = ref([]);
const observerElement = ref(null);

onMounted(() => {
  const observer = new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        // 当触底时加载更多元素
        loadMoreItems();
      }
    });
  });

  observer.observe(observerElement.value);

  // 模拟异步加载更多元素
  const loadMoreItems = async () => {
    // 发起异步请求获取更多数据
    const newItems = await fetchMoreItems();

    // 更新items数组
    items.value = items.value.concat(newItems);
  };

  // 模拟异步请求获取更多数据
  const fetchMoreItems = async () => {
    // 发起异步请求,获取更多数据
    // 返回一个Promise,包含新的元素数组
    // 这里可以根据实际需求来实现数据获取逻辑
    return new Promise(resolve => {
      setTimeout(() => {
        const newItems = [
          { id: 4, name: 'Item 4' },
          { id: 5, name: 'Item 5' },
          { id: 6, name: 'Item 6' }
        ];
        resolve(newItems);
      }, 1000);
    });
  };
});
</script>

In the above example, we use Vue <script setup>syntax and TypeScript, combined with Intersection Observer to realize the function of loading elements at the bottom. The following is the main logic of the code:

  1. refFirst, we created two reactive references using Vue's function: itemsand observerElement.
  2. In onMountedthe hook function, we create an instance of Intersection Observer and set a callback function.
  3. The conditional judgment in the callback function if (entry.isIntersecting)is used to detect observerElementwhether enters the window, if so, call loadMoreItemsthe function to load more elements.
  4. loadMoreItemsThe function simulates the logic of loading more elements asynchronously. It initiates an asynchronous request to obtain new element data and add it to itemsthe array, using concatthe method to merge the original element array and the new element array.
  5. fetchMoreItemsThe function simulates the actual asynchronous request logic. In this example, we've used setTimeoutto simulate a delay, and return a Promise containing the new array of elements.
  6. When the new element array is returned, itemsthe array will be updated, which triggers Vue's responsive update, and then renders the new element in the template.

Through the above code, we have implemented a simple bottom-loading element function. When the user scrolls the page to the bottom, observerElemententers the viewport, triggers the logic to load more elements, and adds the new element to the list.

Summarize

Intersection Observer is a powerful API that provides an efficient and precise way to monitor the intersection state between elements and windows. In this article, we introduced the concept of Intersection Observer and showed how to use it in Vue's development environment to realize the function of loading elements at the bottom. I hope this article can help you better understand and apply Intersection Observer, thereby enhancing your web development experience.

Guess you like

Origin blog.csdn.net/kaka_buka/article/details/131666708