Building an E-Commerce Store - Browsing Products Chapter 10
Looping through products
When looking at a category listing for any shop, the data displayed tends to have a
recurring theme. It normally consists of an image, title, price, and manufacturer.
Add an ordered list to your template – as the products are going to have an order to them,
it makes semantic sense to place them in an ordered list. Within the
- , add a v-for
looping through the products and displaying a title for each one, as shown here. It's also
good practice to ensure the product variable exists before proceeding with displaying it:
template: `<div v-if="products">
<ol>
<li v-for="product in products" v-if="product">
<h3>{{ product.title }}</h3>
</li>
</ol>
</div>`,
When viewing the page in your browser, you may notice that the product list is very long.
Loading images for every one of these products would be a huge load on the user's
computer, along with overwhelming the user with that many products on display. Before
we add more information, such as price and images, to our template, we'll look at
paginating the products, allowing the data to be accessed in more manageable chunks.
Creating pagination
Creating pagination, initially, seems quite simple – as you only need to return a fixed
number of products. However, if we wish to make our pagination interactive and reactive
to the product list – it needs to be a bit more advanced. We need to build our pagination to
be able to handle different lengths of products – in the case where our product list has been
filtered into fewer products.
Calculating the values
The arithmetic behind creating a pagination component and displaying the correct
products relies on four main variables:
Items per page: This is usually set by the user; however, we'll use a fixed number
of 12, to begin with
Total items: This is the total number of products to display