Building an E-Commerce Store - Browsing Products Chapter 10
Creating Vuex getters
The last step to making our category page just like any other shop is the introduction of
filtering. Filtering allows you to find products that have particular sizes, colors, tags, or
manufacturers. Our filtering options are going to be built from the products on the page.
For example, if none of the products have an XL size or a blue color, there is no point
showing that as a filter.
To achieve this, we are going to need to pass the products of the current category to the
filtering component as well. However, the products get processed on the CategoryPage
component. Instead of repeating this processing, we can move the functionality to a Vuex
store getter. Getters allow you to retrieve data from the store and manipulate it like you
would in a function on a component. Because it is a central place, however, it means several
components can benefit from the processing.
Getters are the Vuex equivalent of computed functions. They are declared as functions but
called as variables. However, they can be manipulated to accept parameters by returning a
function inside them.
We are going to move both the category and products functions from the
CategoryPage component into the getter. The getter function will then return an object
with the category and products.
Create a new object in your store titled getters. Inside, create a new function called
categoryProducts:
getters: {
categoryProducts: () => {
}
}
Getters themselves receive two parameters, the state as the first, and any other getters as
the second. To pass a parameter to a getter, you have to return a function inside of the
getter that receives the parameter. Fortunately, in ES2015, this can be achieved with the
double arrow (=>) syntax. As we are not going to be using any other getters in this function,
we do not need to call the second parameter.