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

}

return category;
}
}

In our CategoryPage component, we can remove the products() computed function and


update the category() function. To call a getter function, you refer to


this.$store.getters:


computed: {
category() {
if(Object.keys(this.$store.state.categories).length) {
let category = this.$store.getters.categoryProducts(this.slug);

if(!category) {
this.categoryNotFound = true;
}
return category;
}
}
}

Unfortunately, we are still having to check whether the categories exist before proceeding.
This is so we can tell that there is no category with the name, rather than an unloaded one.


To make this neater, we can extract this check into another getter and utilize it in both our
other getter and the component.


Create a new getter titled categoriesExist, and return the contents of the if statement:


categoriesExist: (state) => {
return Object.keys(state.categories).length;
},

Update the categoryProducts getter to accept getters in the arguments of the first


function and to use this new getter to indicate its output:


categoryProducts: (state, getters) => (slug) => {
if(getters.categoriesExist) {
...
}
}
Free download pdf