JIYIK CN >

Current Location:Home > Learning > WEB FRONT-END > Vue >

Vue - Implementing paging in Vue

Author:JIYIK Last Updated:2025/02/25 Views:

Pagination is one of the common features in modern web applications. It allows users to browse large amounts of data by dividing the data into multiple pages. In Vue, we can use some libraries and components to implement pagination. In this article, we will take a deep dive into how to implement pagination in Vue.

Install and use the Vue pagination component

The Vue pagination component is an easy-to-use plugin that provides functions such as paginator, pagination navigation bar and pagination table. We can install it through the npm package manager:

$ npm install vue-pagination-component --save

Once installed, we can use it in our Vue components:

<template>
  <div>
    <pagination
      :currentPage="currentPage"
      :perPage="perPage"
      :total="total"
      @page-changed="onPageChanged"
    ></pagination>
  </div>
</template>

<script>
import Pagination from 'vue-pagination-component';

export default {
  components: {
    Pagination,
  },
  data() {
    return {
      currentPage: 1,
      perPage: 10,
      total: 100,
    };
  },
  methods: {
    onPageChanged(page) {
      this.currentPage = page;
    },
  },
};
</script>

In the code above, we use a component called pagination. It needs to be passed three properties: currentPage, perPage, and total. It also requires an event handler @page-changedto update the current page number when the paginator's page number changes.

Implementing a custom paginator

If we need more customized functions, we can use a custom paginator to implement the paging function. In Vue, we can use calculated properties and methods to implement a custom paginator.

<template>
  <div>
    <ul>
      <li v-for="page in pages" :key="page">
        <a href="#" @click.prevent="onPageClick(page)">{{ page }}</a>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      currentPage: 1,
      perPage: 10,
      total: 100,
    };
  },
  computed: {
    pages() {
      let pages = [];
      let from = Math.max(1, this.currentPage - 2);
      let to = Math.min(this.currentPage + 2, this.totalPages);

      if (from > 1) {
        pages.push(1);
        if (from > 2) {
          pages.push('...');
        }
      }

      for (let i = from; i <= to; i++) {
        pages.push(i);
      }

      if (to < this.totalPages) {
        if (to < this.totalPages - 1) {
          pages.push('...');
        }
        pages.push(this.totalPages);
      }

      return pages;
    },
    totalPages() {
      return Math.ceil(this.total / this.perPage);
    },
  },
  methods: {
    onPageClick(page) {
      this.currentPage = page;
    },
  },
};
</script>

In the code above, we use a computed property called pages to calculate the page numbers in the paginator. We also use a computed property called totalPages to calculate the total number of pages. Finally, we use a onPageClickmethod called to handle the page number event in the paginator.

Implementing server-side paging

If your data is obtained from the server, you can use server-side paging to implement the paging function. In Vue, we can use the Axios library to obtain server data and use calculated properties and methods to implement server-side paging.

<template>
  <div>
    <ul>
      <li v-for="page in pages" :key="page">
        <a href="#" @click.prevent="onPageClick(page)">{{ page }}</a>
      </li>
    </ul>
    <table>
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
          <th>Email</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="user in users" :key="user.id">
          <td>{{ user.id }}</td>
          <td>{{ user.name }}</td>
          <td>{{ user.email }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      currentPage: 1,
      perPage: 10,
      total: 0,
      users: [],
    };
  },
  computed: {
    pages() {
      let pages = [];
      let from = Math.max(1, this.currentPage - 2);
      let to = Math.min(this.currentPage + 2, this.totalPages);

      if (from > 1) {
        pages.push(1);
        if (from > 2) {
          pages.push('...');
        }
      }

      for (let i = from; i <= to; i++) {
        pages.push(i);
      }

      if (to < this.totalPages) {
        if (to < this.totalPages - 1) {
          pages.push('...');
        }
        pages.push(this.totalPages);
      }

      return pages;
    },
    totalPages() {
      return Math.ceil(this.total / this.perPage);
    },
  },
  methods: {
    onPageClick(page) {
      this.currentPage = page;
      this.getUsers();
    },
    getUsers() {
      axios
        .get(`/api/users?page=${this.currentPage}&per_page=${this.perPage}`)
        .then((response) => {
          this.total = response.data.total;
          this.users = response.data.users;
        })
        .catch((error) => {
          console.log(error);
        });
    },
  },
  mounted() {
    this.getUsers();
  },
};
</script>

In the code above, we use a getUsersmethod called to fetch server data. We also use a lifecycle hook called mounted to fetch server data when the component is mounted. Finally, we use a onPageClickmethod called to handle the page number event in the paginator and re-fetch the server data.


Summarize

In this article, we took a deep dive into how to implement paging in Vue. We introduced methods to implement paging using Vue paging components, custom paginators, and server-side paging. I hope this article can help you better understand the implementation of paging.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Various ways to format dates in Vue

Publish Date:2025/02/26 Views:68 Category:Vue

Vue is a popular front-end framework that provides many features, including multiple ways to format dates. In this article, we will introduce several methods that can help you format dates in Vue. Using moment.js moment.js is a popular

The difference between strict mode and non-strict mode in Vue

Publish Date:2025/02/26 Views:169 Category:Vue

Vue.js is a very popular JavaScript framework. Its design goal is to help developers build efficient and flexible web applications. Vue.js provides two different modes: strict mode and non-strict mode. These two modes are used in the develop

Click the button to switch the background color in vue

Publish Date:2025/02/26 Views:160 Category:Vue

Vue is a popular JavaScript framework for building interactive web applications. Vue provides many powerful features, one of which is the ability to easily toggle the background color when a button is clicked. In this article, we will show y

Introducing the bootstrap framework into the vue project

Publish Date:2025/02/26 Views:148 Category:Vue

Bootstrap is a popular front-end framework that provides a wealth of CSS and JavaScript components to help developers quickly build modern responsive websites and applications. Introducing the Bootstrap framework in a Vue project can provide

Using iframe to nest pages in Vue

Publish Date:2025/02/26 Views:177 Category:Vue

With the development of the Internet, websites are becoming more and more complex, and various technologies are needed to implement them. Among them, iframe technology is a commonly used technology that can embed a web page into another web

Different ways to send POST requests in Vue

Publish Date:2025/02/26 Views:82 Category:Vue

In Vue, sending POST requests is a very common operation, which can be achieved in many ways. This article will introduce several methods of sending POST requests in Vue, and will explain them in detail with examples. Method 1: Use Vue-resou

Importing JSON files into Vue

Publish Date:2025/02/26 Views:100 Category:Vue

Vue.js is a popular JavaScript framework that can quickly build single-page applications (SPA). In Vue.js, we can use JSON files to store data, which is very useful in development. This article will introduce how to introduce JSON files in V

Creating a sticky footer in Vue

Publish Date:2025/02/26 Views:116 Category:Vue

In web design, the footer is one of the most important parts of the page. It usually contains copyright information, contact information, and other relevant information about the website. However, when users scroll the page, the footer may d

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial