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

Filtering the products


Our filters are now being created and appended to dynamically, and activating a filter


updates the query parameter in the URL. We can now proceed with showing and hiding
products based on the URL parameters. We are going to be doing this by filtering the


products before being passed into the ListProducts component. This ensures the


pagination works correctly.


As we are filtering, open up ListProducts.js and add a :key attribute to each list item,


with the value of the handle:


<ol :start="pagination.range.from + 1">
<li v-for="product in paginate(products)" :key="product.handle">
...
</li>
</ol>

Open up the CategoryPage view and create a method within the methods object titled


filtering() and add a return true to begin with. The method should accept two


parameters, a product and query object:


methods: {
filtering(product, query) {

return true;
}
}

Next, within the category computed function, we need to filter the products if there is a


query parameter. However, we need to be careful that we don't trigger the filters if the page


number is present – as that is also a query.


Create a new variable called filters, which is a copy of the query object from the route.


Next, if the page parameter is present, delete it from our new object. From there, we can


check whether the query object has any other contents and if so, run the native JavaScript
filter() function on our product array – passing in the product and new query/filters


object to our method:


category() {
if(this.categoriesExist) {
let category = this.categoryProducts(this.slug),
filters = Object.assign({}, this.$route.query);

if(Object.keys(filters).length && filters.hasProperty('page')) {
delete filters.page;
Free download pdf