lazy loading by scroll vue

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

<script>
export default {
  data() {
    return {
      items: [],
      page: 1,
      loading: false,
    };
  },
  mounted() {
    this.fetchData();

    const observer = new IntersectionObserver(this.handleIntersection, {
      root: null,
      rootMargin: "0px",
      threshold: 0.1,
    });

    observer.observe(this.$refs.sentinel);
  },
  methods: {
    fetchData() {
      if (this.loading) return;

      this.loading = true;

      // Simulating an API call, replace this with your actual API call
      setTimeout(() => {
        const newItems = Array.from({ length: 10 }, (_, index) => ({
          id: this.items.length + index + 1,
          name: `Item ${this.items.length + index + 1}`,
        }));

        this.items = [...this.items, ...newItems];
        this.loading = false;
      }, 1000);
    },
    handleIntersection(entries) {
      const entry = entries[0];
      if (entry.isIntersecting) {
        this.page++;
        this.fetchData();
      }
    },
  },
};
</script>

In this example:

  1. The template defines a container div for displaying items and includes a div with the ref attribute set to "sentinel," which will be used as a sentinel element to trigger the lazy loading.

  2. The script section of the component exports a Vue component with data properties for items, page, and loading. The mounted lifecycle hook initializes the component by calling the fetchData method and sets up an IntersectionObserver to monitor the sentinel element.

  3. The fetchData method simulates an API call by setting a timeout and then appends new items to the items array. The method also sets the loading flag to prevent multiple simultaneous requests.

  4. The handleIntersection method is called when the sentinel element comes into view. It increments the page and calls the fetchData method to load more items.

  5. The v-for directive in the template iterates over the items array, rendering each item's name in a div.

This implementation demonstrates lazy loading of items by fetching additional data when the user scrolls to the bottom of the page. Adjust the fetchData method to make actual API calls and modify the item rendering based on your specific use case.