DEV Community

Pulkit Singh
Pulkit Singh

Posted on • Updated on

Easy and Simple Pagination in Vue

How to paginate simply by using vue js?

In this tutorial I will show you how to Add custom Pagination in a vue component.

<template>
  <div id="app">
    <table>
      <thead>
        <th>#</th>
        <th>Name</th>
        <th>Age</th>
      </thead>
      <tbody>
        <tr v-for="(item, index) in currentList" :key="index">
          <td>{{ item.index }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
        </tr>
      </tbody>
    </table>
    <button v-on:click="previousPage()" v-if="currentPage > 1">previous</button>
    <button v-on:click="nextPage()">Next</button>
  </div>
</template>

<script>
export default {
  created() {
    this.persons.map((n) => {
      this.num++;
      n.index = this.num;
      return n;
    });
    this.makeCurrentList();
  },
  data() {
    return {
      persons: [
        { name: "kapil", age: 22 },
        { name: "pulkit", age: 23 },
        { name: "rajat", age: 24 },
        { name: "raj", age: 25 },
        { name: "ankit", age: 26 },
        { name: "abhay", age: 27 },
        { name: "anmol", age: 28 },
        { name: "ishaan", age: 29 },
        { name: "ayush", age: 30 },
        { name: "rajat", age: 24 },
        { name: "raj", age: 25 },
        { name: "ankit", age: 26 },
        { name: "abhay", age: 27 },
        { name: "anmol", age: 28 },
        { name: "kapil", age: 22 },
        { name: "pulkit", age: 23 },
        { name: "rajat", age: 24 },
        { name: "raj", age: 25 },
        { name: "ankit", age: 26 },
        { name: "abhay", age: 69 },
      ],
      itemPerPage: 5,
      currentPage: 1,
      currentList: [],
      startIndex: null,
      num: 0,
    };
  },
  methods: {
    previousPage() {
      this.currentPage--;
      this.makeCurrentList(this.currentPage);
    },
    nextPage() {
      this.currentPage++;
      this.makeCurrentList(this.currentPage);
    },
    makeCurrentList() {
      this.currentList = [];
      console.log(this.currentPage);
      this.startIndex = this.currentPage * this.itemPerPage - this.itemPerPage;
      this.currentList = this.persons.slice(
        this.startIndex,
        this.currentPage * this.itemPerPage
      );
      console.log("start Index => ", this.startIndex);
      console.log("current Page => ", this.currentPage);
      console.log("Current List => ", this.currentList);
    },
  },
  name: "App",
  components: {},
};
</script>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)