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

Set the currentPage variable back to 1 and load the home page up in the browser. You


should notice the Previous page button is disabled. If you change the currentPage


variable, you will notice the buttons become active and inactive as desired.


We now need to create a click method for the buttons to update the currentPage. Create a


new function titled toPage(). This should accept a single variable – this will directly


update the currentPage variable:


methods: {
toPage(page) {
this.currentPage = page;
},

paginate(list) {
return list.slice(this.pagination.range.from,
this.pagination.range.to);
}
}

Add the click handlers to the buttons, passing through currentPage + 1 for the Next


page button, and currentPage - 1 for the Previous page button:


template: `<div v-if="products">
<button @click="toPage(currentPage - 1)" :disabled="currentPage ==
1">Previous page</button>
<button @click="toPage(currentPage + 1)" :disabled="currentPage ==
pagination.totalPages">Next page</button>

<ol :start="pagination.range.from + 1">
<li v-for="product in paginate(products)" v-if="product">
<h3>{{ product.title }}</h3>
</li>
</ol>
</div>`

We can now navigate back and forth through the products. As a nice addition to the user


interface, we could give an indication of the page number and how many pages remain,


using the variables available to us by using the code mentioned here:


template: `<div v-if="products">
<p>
Page {{ currentPage }} out of {{ pagination.totalPages }}
</p>
<button @click="toPage(currentPage - 1)" :disabled="currentPage ==
1">Previous page</button>
<button @click="toPage(currentPage + 1)" :disabled="currentPage ==
pagination.totalPages">Next page</button>
Free download pdf