Infinite scrolling is a technique used in web development to load more content as the user scrolls down a page. In Vue.js, you can implement infinite scrolling using a combination of Vue directives, methods, and event listeners. Here's a simple example of how you can achieve infinite scrolling in Vue.js:
html<template>
<div>
<div v-for="item in items" :key="item.id">
<!-- Render your items here -->
{{ item.text }}
</div>
<div ref="scrollObserver" @scroll="handleScroll" style="height: 400px; overflow-y: auto;">
<!-- Content container with a fixed height and scroll -->
<!-- This is the container that will trigger the infinite scroll -->
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [], // Array to hold your items
page: 1, // Initial page number
isLoading: false, // Flag to track if data is being loaded
};
},
methods: {
// Function to load more data
loadData() {
// Simulate an API call or fetch data
// Replace this with your actual data fetching logic
const newData = /* Your data fetching logic here */;
// Append new data to the items array
this.items = [...this.items, ...newData];
// Increment the page number for the next request
this.page++;
// Set isLoading to false to allow more requests
this.isLoading = false;
},
// Function to handle scroll events
handleScroll() {
// Check if the user has scrolled to the bottom of the container
const container = this.$refs.scrollObserver;
if (container.scrollTop + container.clientHeight >= container.scrollHeight && !this.isLoading) {
// Set isLoading to true to prevent multiple simultaneous requests
this.isLoading = true;
// Call the function to load more data
this.loadData();
}
},
},
mounted() {
// Call the initial data load
this.loadData();
},
};
</script>
In this example:
items
array holds the data you want to display.loadData
method simulates fetching more data (replace this with your actual data fetching logic).handleScroll
method is called when the user scrolls. It checks if the user has reached the bottom of the scrollable container and triggers the loadData
method if conditions are met.mounted
lifecycle hook is used to load initial data when the component is mounted.Note: Make sure to adjust the data fetching logic in the loadData
method based on your application's requirements.