Pagination in Vue.js

Hi, Habr! I present to you the translation of the article " Pagination in Vue.js " by Denny Headrick.

Pagination increases UX, allowing users to visualize data in small blocks or on pages. That's the component Vue.js can be made broken down by pages, which will allow us to view only part of our data at a time.



First, I will add piece by piece to my JavaScript object. And then show : template (template)

Of all the local data I need only the data - page number.

data(){
    return {
      pageNumber: 0// по умолчанию 0
    }
}

For props (properties), data transfer is mandatory, but I will also take the size argument for the maximum number of entries.

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

For my implementation, I will use the methods to go to the previous (previous) and next (next) pages:

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

Computed's fast calculated property to find out how many pages there are:

pageCount(){
      let l = this.listData.length,
          s = this.size;
      // редакция переводчика спасибо комментаторамreturnMath.ceil(l/s);
      // оригинал// return Math.floor(l/s);
}


Now the calculated property ( COMPUTED ) paginatedData  - is the place where everything comes together. This is the filtered data that will be displayed.

paginatedData(){
    const start = this.pageNumber * this.size,
          end = start + this.size;
    returnthis.listData.slice(start, end);
}

Editorial : I initially did something terrible and cumbersome to copy an array. Using  .slice  is the best approach. Thank you, Alexander Karelas .

And our : template (template)

<div><ul><liv-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 the buttons to work when they should. For the prevPage button , I add: 
: disabled = "pageNumber == 0"
and for the nextPage button , add: 
: disabled = "pageNumber> = pagecount -1"
Working demonstration of my component:


Sometimes it is difficult to overestimate the situation, but pagination is a simple function that we can offer our users without much effort.

Thanks for reading!

Denny Headrick is a USAF web developer who loves his job too much. In addition to developing on various platforms and Vue.js, when he can, he likes to blog occasionally. You can follow him on Twitter at @dennythecoder.

Also popular now: