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

The issue with this is if the user is on a page higher than is possible once the value has


changed. For example, if there are 30 products with 12 products per page, this would create
three pages. If the user navigates to page three and then selects 24 products per page, there


would only be two pages needed and page three would be empty.


This can be resolved, once again, with a watch function. When the perPage variable


updates, we can check if the current page is higher than the totalPages variable. If it is,


we can redirect it to the last page:


watch: {
'$route'(to) {
this.currentPage = parseInt(to.query.page);
},

perPage() {
if(this.currentPage > this.pagination.totalPages) {
this.$router.push({
query: Object.assign({}, this.$route.query, {
page: this.pagination.totalPages
})
})
}
}
}

Creating the ListProducts component


Before we proceed with creating the filtering and ordering, we need to extract our product
listing logic and template it into our component – allowing us to easily reuse it. This


component should accept a prop of products, which it should be able to list and paginate.


Open up the ListProducts.js file and copy the code from the HomePage.js file into the


component. Move the data object and copy the pagination and pageLinks computed


functions. Move the watch and methods objects, as well as the created() function, from


the HomePage to the ListProducts file.


Update the HomePage template to use the components with a


products prop, passing in the products computed value. In comparison, the HomePage


component should now be significantly smaller:


const HomePage = {
name: 'HomePage',
Free download pdf