Building an E-Commerce Store - Browsing Products Chapter 10
This can be done using the created() function – updating the variables – ensuring we've
checked for its existence first. The created function is part of the Vue life cycle and was
covered in Chapter 4, Getting a List of Files Using the Dropbox API:
created() {
if(this.$route.query.page) {
this.currentPage = parseInt(this.$route.query.page);
}
}
We need to ensure the currentPage variable is an integer, to help us with any arithmetic
we need to do later on as a string is not a fan of calculations.
Creating pagination links
When viewing paginated products, it's often good practice to have a truncated list of page
numbers, allowing the user to jump several pages. We already have the mechanism for
navigating between pages – this can extend that.
As a simple entry point, we can create a link to every page by looping through until we
reach the totalPages value. Vue allows us to do this without any JavaScript. Create a nav
element at the bottom of the component with a list inside. Using a v-for, and create a
variable of page for every item in the totalPages variable:
<nav>
<ol>
<li v-for="page in pagination.totalPages">
<button @click="toPage(page)">{{ page }}</button>
</li>
</ol>
</nav>
This will create a button for every page – for example, if there are 24 pages in total, this will
create 24 links. This is not the desired effect, as we want a few pages before and after the
current page. An example of this would be, if the current page is 15, the page links should
be 12, 13, 14, 15, 16, 17 and 18. This means there are fewer links and it is less overwhelming
for the user.