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:
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.The script section of the component exports a Vue component with data properties for
items
,page
, andloading
. Themounted
lifecycle hook initializes the component by calling thefetchData
method and sets up anIntersectionObserver
to monitor the sentinel element.The
fetchData
method simulates an API call by setting a timeout and then appends new items to theitems
array. The method also sets theloading
flag to prevent multiple simultaneous requests.The
handleIntersection
method is called when the sentinel element comes into view. It increments thepage
and calls thefetchData
method to load more items.The
v-for
directive in the template iterates over theitems
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.