Home Web Front-end Vue.js How to implement infinite scroll loading and paging display in Vue components

How to implement infinite scroll loading and paging display in Vue components

Oct 09, 2023 pm 04:01 PM
load infinite scroll Paginated display

How to implement infinite scroll loading and paging display in Vue components

How to implement infinite scrolling loading and paging display in Vue components

In front-end development, we often encounter situations where a large amount of data needs to be displayed. In order to improve user experience, we usually display the data in pages and automatically load the next page of data when scrolling to the bottom of the page. This article will introduce how to use Vue components to implement infinite scrolling loading and paging display functions, and give specific code examples.

First, we need to prepare the backend interface for obtaining paging data. Suppose we have an interface /api/data, through which we can obtain the data list of the specified page number (page). The data format returned by the interface is as follows:

{
  "total": 100, // 总数据条数
  "list": [...] // 当前页的数据列表
}
Copy after login

Next, we can use Vue’s component development idea to encapsulate the functions of scrolling loading and paging display into an independent component. We can call it the InfiniteScroll component. First, we need to introduce the component in the parent component and pass in the necessary parameters.

<template>
  <div>
    <infinite-scroll
      :api-url="'/api/data'" // 后端接口地址
      :page-size="10" // 每页数据条数
      @load-next-page="loadNextPage"
    >
      <!-- 数据展示的代码 -->
    </infinite-scroll>
  </div>
</template>
Copy after login

In the InfiniteScroll component, we need to listen to the scroll event and trigger the operation of loading the next page of data when scrolling to the bottom of the page. We can use the scroll event of the window object to listen for scroll events.

export default {
  data() {
    return {
      page: 1, // 当前页码
      total: 0, // 总数据条数
      list: [] // 当前页的数据列表
    };
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll);
  },
  destroyed() {
    window.removeEventListener('scroll', this.handleScroll);
  },
  methods: {
    handleScroll() {
      const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
      const windowHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
      const documentHeight = document.documentElement.scrollHeight || document.body.scrollHeight;

      if (scrollTop + windowHeight >= documentHeight) {
        this.loadNextPage();
      }
    },
    async loadNextPage() {
      if (this.page >= Math.ceil(this.total / this.pageSize)) {
        return; // 已加载所有数据
      }

      const response = await fetch(`${this.apiUrl}?page=${this.page + 1}`);
      const result = await response.json();

      this.total = result.total;
      this.list = [...this.list, ...result.list];
      this.page++;
    }
  }
};
Copy after login

In the above code, we use the window.addEventListener method to add a scroll event listener to trigger the loading of the next page of data when scrolling to the bottom of the page. At the same time, you need to use the window.removeEventListener method to remove the scroll event listener when the component is destroyed.

In the handleScroll method, we first obtain the current scrolling position, including the page scrolling distance (scrollTop), the height of the window (windowHeight) and the total height of the document (documentHeight). Then it is determined that when the scroll position plus the height of the window is greater than or equal to the total height of the document, it means that the page has been scrolled to the bottom, and the operation of loading the next page of data will be triggered.

In the loadNextPage method, we first determine whether all data has been loaded, that is, whether the current page number is greater than the total number of data pages. If all data has been loaded, return directly. Otherwise, obtain the next page of data through an asynchronous request, merge the returned data into the original data list, and update the current page number and total number of data items at the same time.

Finally, inside the InfiniteScroll component, we can display it accordingly based on the obtained data.

<template>
  <div>
    <ul>
      <li v-for="item in list" :key="item.id">{{ item.name }}</li>
    </ul>
    <div v-if="page >= Math.ceil(total / pageSize)">已加载所有数据</div>
  </div>
</template>
Copy after login

In the above code, we traverse the data list through the v-for instruction and use the id attribute of each element as the key, ensure the uniqueness of list elements. At the same time, we add a prompt at the bottom of the component. When the page number is greater than or equal to the total number of data pages, the prompt message "All data has been loaded" is displayed.

To sum up, by introducing the InfiniteScroll component and giving the corresponding parameters, we can realize the functions of infinite scroll loading and paging display. By listening to scroll events, the next page of data is automatically loaded when scrolling to the bottom of the page to achieve the effect of infinite scroll loading. At the same time, by updating the data of the component, page display is performed based on the number of data items on each page and the total number of data items.

I hope the code examples provided in this article will be helpful to you and enable you to implement infinite scroll loading and paging display functions in Vue components. If you have any questions or suggestions for improvements, please leave a message for discussion.

The above is the detailed content of How to implement infinite scroll loading and paging display in Vue components. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Error loading plugin in Illustrator [Fixed] Error loading plugin in Illustrator [Fixed] Feb 19, 2024 pm 12:00 PM

When launching Adobe Illustrator, does a message about an error loading the plug-in pop up? Some Illustrator users have encountered this error when opening the application. The message is followed by a list of problematic plugins. This error message indicates that there is a problem with the installed plug-in, but it may also be caused by other reasons such as a damaged Visual C++ DLL file or a damaged preference file. If you encounter this error, we will guide you in this article to fix the problem, so continue reading below. Error loading plug-in in Illustrator If you receive an "Error loading plug-in" error message when trying to launch Adobe Illustrator, you can use the following: As an administrator

Stremio subtitles not working; error loading subtitles Stremio subtitles not working; error loading subtitles Feb 24, 2024 am 09:50 AM

Subtitles not working on Stremio on your Windows PC? Some Stremio users reported that subtitles were not displayed in the videos. Many users reported encountering an error message that said "Error loading subtitles." Here is the full error message that appears with this error: An error occurred while loading subtitles Failed to load subtitles: This could be a problem with the plugin you are using or your network. As the error message says, it could be your internet connection that is causing the error. So please check your network connection and make sure your internet is working properly. Apart from this, there could be other reasons behind this error, including conflicting subtitles add-on, unsupported subtitles for specific video content, and outdated Stremio app. like

PHP implements infinite scroll loading PHP implements infinite scroll loading Jun 22, 2023 am 08:30 AM

With the development of the Internet, more and more web pages need to support scrolling loading, and infinite scrolling loading is one of them. It allows the page to continuously load new content, allowing users to browse the web more smoothly. In this article, we will introduce how to implement infinite scroll loading using PHP. 1. What is infinite scroll loading? Infinite scroll loading is a method of loading web content based on scroll bars. Its principle is that when the user scrolls to the bottom of the page, background data is asynchronously retrieved through AJAX to continuously load new content. This kind of loading method

Outlook freezes when inserting hyperlink Outlook freezes when inserting hyperlink Feb 19, 2024 pm 03:00 PM

If you encounter freezing issues when inserting hyperlinks into Outlook, it may be due to unstable network connections, old Outlook versions, interference from antivirus software, or add-in conflicts. These factors may cause Outlook to fail to handle hyperlink operations properly. Fix Outlook freezes when inserting hyperlinks Use the following fixes to fix Outlook freezes when inserting hyperlinks: Check installed add-ins Update Outlook Temporarily disable your antivirus software and then try creating a new user profile Fix Office apps Program Uninstall and reinstall Office Let’s get started. 1] Check the installed add-ins. It may be that an add-in installed in Outlook is causing the problem.

How to solve the problem that css cannot be loaded How to solve the problem that css cannot be loaded Oct 20, 2023 am 11:29 AM

The solutions to the problem that CSS cannot be loaded include checking the file path, checking the file content, clearing the browser cache, checking the server settings, using developer tools and checking the network connection. Detailed introduction: 1. Check the file path. First, please make sure the path of the CSS file is correct. If the CSS file is located in a different part or subdirectory of the website, you need to provide the correct path. If the CSS file is located in the root directory, the path should be direct. ; 2. Check the file content. If the path is correct, the problem may lie in the CSS file itself. Open the CSS file to check, etc.

How to build infinite scroll and waterfall flow layout using Vue? How to build infinite scroll and waterfall flow layout using Vue? Jun 27, 2023 pm 01:32 PM

Vue.js is a popular JavaScript framework that allows developers to easily create dynamic, responsive web applications. Among them, it is especially favored by developers for its powerful component development capabilities. Infinite scrolling and waterfall flow layout have become one of the indispensable features in modern web development. This article aims to introduce how to use Vue.js, combined with some third-party libraries, to implement infinite scrolling and waterfall flow layout functions. Achieve infinite scroll infinite scroll (Infinit

How to create an infinite scrolling news list using HTML, CSS and jQuery How to create an infinite scrolling news list using HTML, CSS and jQuery Oct 24, 2023 am 11:00 AM

How to create an infinite scrolling news list using HTML, CSS and jQuery In web development, infinite scrolling is a common interaction technology, especially suitable for pages such as news lists that need to load a large amount of data. This article will introduce how to use HTML, CSS and jQuery to implement an infinite scrolling news list, and provide specific code examples. First, we need a basic HTML structure to display the news list. Here's a simple example: &lt;!DOCTYPE

How to implement infinite scrolling to optimize application performance through Vue's virtual list How to implement infinite scrolling to optimize application performance through Vue's virtual list Jul 17, 2023 am 08:55 AM

How to optimize application performance through infinite scrolling through Vue's virtual list. As the complexity of front-end applications continues to increase, especially when processing large amounts of data, some performance issues also arise. In this regard, Vue provides a powerful tool - virtual list (VirtualList), which can greatly improve application performance when processing large amounts of data by dynamically rendering visible elements in the list. This article will introduce how to use Vue's virtual list to implement infinite scrolling and optimize application performance. We will use a virtual address book

See all articles