Complete Vue.js 2 Web Development_ Practical guide to building end-to-end web development solutions with Vue.js 2

(singke) #1
Building an E-Commerce Store - Browsing Products Chapter 10

For example, if you were showing 12 items per page and you had 14 products, that would


yield a result of 1.1666 pages – which is not a valid page number. Rounding this up ensures


we have two pages to display our products. To do this, use the Math.ceil() JavaScript


function. We can also add the total number of products to our output. Check the following


code for using the Math.ceil() function:


pagination() {
if(this.products) {
let totalProducts = this.products.length;
return {
totalProducts: totalProducts,
totalPages: Math.ceil(totalProducts / this.perPage)
}
}
}

The next calculation we need to do is work out what the current range of products for the
current page is. This is a little more complicated, as not only do we need to work out what


we need from the page number, but the array slicing is based on the item index – which


means the first item is 0.


To work out where to take our slice from, we can use the following calculation:


(current page number * items per page) – items per page


The final subtraction may seem odd, but it means on page 1 , the result is 0. This allows us


to work out at which index we need to slice the products array.


As another example, if we were on page three, the result would be 24, which is where the


third page would start. The end of the slice is then this result plus the number of items per
page. The advantage of this means we can update the items per page and all of our


calculations will update.


Create an object inside the pagination result with these two results – this will allow us to


access them later easily:


pagination() {
if(this.products) {
let totalProducts = this.products.length,
pageFrom = (this.currentPage * this.perPage) - this.perPage;
return {
totalProducts: totalProducts,
totalPages: Math.ceil(totalProducts / this.perPage),
range: {
from: pageFrom,
Free download pdf