Building an E-Commerce Store - Browsing Products Chapter 10
}
}
Within the data function, change the value of topics to be this.defaultTopics() to call
the method:
data() {
return {
topics: this.defaultTopics()
}
},
Lastly, add a watch function to reset the topics key when the slug gets updated:
watch: {
slug() {
this.topics = this.defaultTopics();
}
}
Updating the URL on checkbox filter change
Our filtering component, when interacted with, is going to update the URL query
parameters. This allows the user to see the filters in effect, bookmark them, and share the
URL if needed. We already used query parameters for our pagination, and it makes sense
to put the user back on page one when filtering – as there may only be one page.
To construct our query parameters of filters, we need to loop through each filter type and
add a new parameter for each one that has items in the checked array. We can then call a
router.push() to update the URL and, in turn, change the products displayed.
Create an empty object in your updateFilters method. Loop through the topics and
populate the filters object with the items checked. Set the query parameters in the
router to the filters object:
updateFilters() {
let filters = {};
Object.keys(this.topics).forEach(key => {
let topic = this.topics[key];
if(topic.checked.length) {
filters[key] = topic.checked;
}
});