Pagination in Vue JS

Pagination enhances UX by allowing users to visualize data in smaller chunks, or pages. Here’s how to go about making a Vue.js component with pagination that allows us to only view parts of our data at a time.


I’ll go piece by piece in our JavaScript object first, and then show the template.

The only local data I need is the page number.

data(){  
    return {  
      pageNumber: 0  // default to page 0  
    }  
}

For props, passing the data is a must, but I’ll also take a size argument for the max number of records.

props:{  
    listData:{  
      type:Array,  
      required:true  
    },  
    size:{  
      type:Number,  
      required:false,  
      default: 10  
    }  
}

For my methods, I’ll use methods to go to the previous and next pages:

methods:{  
      nextPage(){  
         this.pageNumber++;  
      },  
      prevPage(){  
        this.pageNumber--;  
      }  
}

A quick computed property to figure out how many pages there are:

pageCount(){  
      let l = this.listData.length,  
          s = this.size;  
      return Math.ceil(l/s);  
}

Now, the paginatedData computed property is where it comes together. This is the filtered data that will be rendered.

paginatedData(){  
    const start = this.pageNumber \* this.size,  
          end = start + this.size;

     return this.listData.slice(start, end);  
}

Edit: I was initially doing something funky to copy the array while using _.splice._ Using _.slice_ is the better approach. Thanks Alexander Karelas.

And for the template:

<div>  
  <ul>  
    <li v-for="p in paginatedData">  
      {{p.first}}   
      {{p.last}}    
      {{p.suffix}}  
    </li>  
  </ul>  
  <button @click="prevPage">  
    Previous  
  </button>  
  <button @click="nextPage">  
    Next  
  </button>  
</div>

I want to prevent the buttons from working when they should. For the prevPage button, I will add :disabled="pageNumber==0" and for the nextPage button, I will add :disabled="pageNumber >= pagecount -1".

It can be easy to overthink things sometimes, but pagination is a straightforward feature that we can offer to our users without a lot of effort.

Thanks for reading!

Denny Headrick is a software lead for the USAF that likes his work way too much. On top of developing on a variety of platforms and with Vue.js when he can, he likes to blog occasionally. You can follow him on Twitter at @dennythecoder.

By Denny Headrick on January 4, 2018.

You may also like

  • Use HTML Semantically

    After years of hacks using tables for positioning elements with tables, you may be surprised to find that HTML has become increasingly expressive.

    Read More >
  • Java 8 Lambdas

    In this post, I discuss my brief experience with Java 8's lambdas and thoughts about them.

    Read More >