Navigating websites with traditional pagination can sometimes feel cumbersome, requiring users to constantly move the mouse and click the next button. An alternative approach is the infinite scroll method, which offers a seamless browsing experience. This post introduces two methods to implement infinite scroll using Vue.js, making website exploration more user-friendly.
1. Event Listener
In this method we can use template ref and add event listener to container or we can also use window
.
<script setup> import { ref, onMounted, onUnmounted } from 'vue'; const results = ref([]); const element = ref(); const loadMore = () => { const bottom = element.value.getBoundingClientRect().bottom < window.innerHeight; if (bottom) { getData(); } }; const getData = async () => { const url = `api url`; const response = await fetch(url); const data = await response.json(); results.value = [...results.value, ...data]; } onMounted(() => { getData(); window.addEventListener('scroll', loadMore); }); onUnmounted(() => { window.removeEventListener('scroll', loadMore) }) </script> <template> <div ref="element"> <div v-for="result in results"> <!-- your content right here --> </div> </div> </template>
2. VueUse Package
VueUse is a collection of utility functions based on Composition API. You can read the doc here.
First, we need to install package
npm i @vueuse/core
And then in your vue component use useInfiniteScroll
function
<script setup> import { useInfiniteScroll } from '@vueuse/core'; import { ref, onMounted } from 'vue'; const element = ref(document); const results = ref([]); useInfiniteScroll(element, () => { getData() }, { distance: 10 }); const getData = async () => { const url = `api url`; const response = await fetch(url); const data = await response.json(); results.value = [...results.value, ...data]; } onMounted(() => { getData() }); </script> <template> <div v-for="result in results"> <!-- your content right here --> </div> </template>
For a demo and source code, you can follow this link and this link.