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

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

WBOY
WBOYOriginal
2023-10-09 16:01:441122browse

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": [...] // 当前页的数据列表
}

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>

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++;
    }
  }
};

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>

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:
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