How to Implement Infinite Scrolling in Vue

Infinite Scrolling is useful when you need to show large chunks of data in your application. In this article, let's learn together how to create Infinite Scrolling - endless loading in Vue!

Picture 1 of How to Implement Infinite Scrolling in Vue

Infinite Scrolling is a technique that you can use to show more content as the app user scrolls down the page. It eliminates the need for pagination, and allows app users to continue scrolling or loading through large data sets.

Set up Vue . app

To follow this tutorial, you need a basic knowledge of Vue 3 and JavaScript. You should know how to handle HTTP queries with Axios.

To start learning how to implement endless scrolling, create a new Vue app by running the following npm command in your preferred directory:

npm create vue

While setting up the project, Vue will prompt you to choose a preset for the application. Select No for all features, as you won't need to add them to the app.

Picture 2 of How to Implement Infinite Scrolling in Vue

 

Once you've created your new app, navigate to your app's directory and run the following npm command to install the necessary packages:

npm install axios @iconify/vue @vueuse/core

The npm command installs 3 packages: axios (for HTTP queries), @iconify/vue (for easy icon integration in Vue) and @vueuse/core (provides necessary Vue features).

You will use axios and @iconify/vue to fetch data and add icons to the app. @vueuse/core contains Vue widgets, including the useInfiniteScroll component for endless loading.

Fetching dummy data from JSONPlaceholder API

To implement infinite scrolling, you need data. You can hard-code the data or get it from a free pseudo-API source like JSONPlaceholder.

Getting these data from JSONPlaceholder simulates real-life scenarios, because most web applications get data from the database instead of hard-coded data.

To fetch data from the API for a Vue app, create a new folder in the src directory and name it api . In that folder, create a new JavaScript file and paste the following code:

//getComments.js import axios from "axios"; async function getComments(max, omit) { try { const comments = await axios.get( `https://jsonplaceholder.typicode.com/comments?_limit=${max}&_start=${omit}` ); return comments.data.map((comment) => comment.body); } catch (error) { console.error(error); } } export default getComments;

This code includes an asynchronous function to get comments from the API endpoint 'https://jsonplaceholder.typicode.com/comments' . It will then output this function.

To elaborate further, the code begins with importing the axios library. This code then defines a getComments function with two arguments: max and omit.

The getComments function contains the axios.get() method that generates a GET query for the URL. This URL contains the query parameters max and omit, interpolated in the string using the pattern character ( `` ). This allows you to pass dynamic values ​​into the URL.

This function then returns a new array containing the bodies of comments received from the API endpoint using the map function .

 

If any error occurs, this code logs it to the console. The code then outputs this function to another part of the application.

Creating Infinite Scroll Components

Now that you've handled the logic for fetching the dummy data, you can create a new component to display the dummy data and handle the infinite load functionality.

Add the new file InfiniteScroll.vue in the src/components folder and add the following code:

 

The above code describes the InfiniteScroll component's script block .

This code imports the ref and useInfiniteScroll functions from vue and @vueuse/core respectively. The code also imports the getComments function from the getComments.js file .

Then this snippet creates a listEl reference with the ref function. listEl references the DOM element with the endless load scroll function.

The variable commentsDisplayed represents the number of comments to initially display on the tang. commentsList contains the array of comments that the code finds using the getComments function .

This fragment contains the commentsToDisplayOnScroll asynchronous function that finds new comments with the getComments function and appends them to the commentsList array using the expansion operator (.).

Finally, this code calls the useInfiniteScroll function to trigger an endless scroll action that takes 3 arguments:

  1. The DOM element (listEl) represents the list that the user of the application will scroll through.
  2. The async function calls when the user scrolls to trigger fetching new comments and appends them to the commentsList .
  3. An optional configuration object with properties. The { distance: 10 } object specifies that new comments should start loading when the user is 10 pixels from the end of the list.

Using the Infinite Scroll component

After handling the endless loading logic in InfiniteScroll 's script block , you need to display the content in the template block.

Paste the following code inside the InfiniteScroll component :

 
  1. {{ comments }}

This code block defines the template for the Vue component responsible for displaying a comment list.

 

Component contains a collection of components

created with the v-for command (to show the list), iterates over the commentsList array .

Each comment from the array is shown in the element

  1. use data interpolation ({{ comment }}). This block of code assigns the listEl reference to trigger the endless scrolling function.

You can then use the InfiniteScroll component in the App.vue file .

 

The above code block imports InfiniteScroll and Icon components. Then it wraps InfiniteScroll into Suspense .

The Suspense component allows you to show fallback content (an icon) when Vue resolves all the asynchronous functionality in the InfiniteScroll component.

You can now preview your app by running the command npm run dev in your app's directory. You will see an interface similar to the image below:

Picture 3 of How to Implement Infinite Scrolling in Vue

The preview window above shows 10 comments because you set the c commentsToBeDisplayed variable to 10. As you scroll down, the app loads more comments to read.

The endless scrolling technique is popular among web applications, especially in social networking apps like X, TikTok.

This technique ensures app users stay engaged as the app continually fetches more data, providing them with an ever-expanding stream of content to read, learn about, and watch, so they're always excited to see surf the page.

Update 17 August 2023
Category

System

Mac OS X

Hardware

Game

Tech info

Technology

Science

Life

Application

Electric

Program

Mobile