Building an E-Commerce Store - Browsing Products Chapter 10
Create a data function on your HomePage component, that which includes an array
titled selectedProducts:
data() {
return {
selectedProducts: []
}
},
Populate the array with several handles from the product list. Try and get about six, but if
you go over 12, remember it will paginate with our component. Add your selected handles
to the selectedProducts array:
data() {
return {
selectedProducts: [
'adjustable-stem',
'colorful-fixie-lima',
'fizik-saddle-pak',
'kenda-tube',
'oury-grip-set',
'pure-fix-pedals-with-cages'
]
}
},
With our selected handles, we can now filter the product list to only include a list of
products included in our selectedProducts array. The initial instinct might be to use the
JavaScript filter() function on the products array combined with includes():
products() {
let products = this.$store.state.products;
products = Object.keys(products).map(key => products[key]);
products = products.filter(product =>
this.selectedProducts.includes(product.handle));
return products;
}
The issue with this is that, although it appears to work, it does not respect the ordering of
the selected products. The filter function simply removes any items that do not match and
leaves the remaining products in the order they are loaded.
Fortunately, our products are saved in a key/value pair with the handle as the key. Using
this, we can utilize the products object and return an array using a for loop.