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

negativePoint = 1;
}

if(positivePoint > this.pagination.totalPages) {
positivePoint = this.pagination.totalPages;
}

for (var i = negativePoint; i <= positivePoint; i++) {
pages.push(i)
}

return pages;
}
}

We can now replace the pagination.totalPages variable in our navigation component


with the new pageLinks variable and the correct number of links will be created, as shown


here:


<nav>
<ul>
<li v-for="page in pageLinks">
<button @click="toPage(page)">{{ page }}</button>
</li>
</ul>
</nav>

Viewing this in the browser, however, will render some odd behavior. Although the correct


number of links will be generated, clicking on them or using the next/previous buttons will
cause the buttons to remain the same – even if you navigate out of the range of the buttons.


This is because the computed value is cached. We can combat this in two ways – either


move the function into the method object or, alternatively, add a watch function to watch


the route and update the current page.


Opting for the second option means we can ensure no other results and outputs get cached


and are updated accordingly. Add a watch object to your component and update the


currentPage variable to that of the page query variable. Ensure it exists, otherwise default


to one. The watch method is as shown here:


watch: {
'$route'(to) {
this.currentPage = parseInt(to.query.page) || 1;
}
}
Free download pdf