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

Creating the category list like this means we readily have available the list of products


within the category while being able to loop through the categories and output the title


and handle to create a list of links to categories. As we already have this information, we


will create the category list once we've retrieved the product list.


Open up app.js and navigate to the created() method on the Vue instance. Rather than


creating a second $store.commit underneath the products storing method, we are going


to utilize a different functionality of Vuex – actions.


Actions allow you to create functions in the store itself. Actions are unable to mutate the
state directly – that is still down to mutations, but it allows you to group several mutations


together, which in this instance, suits us perfectly. Actions are also perfect if you want to


run an asynchronous operation before mutating the state – for example with a setTimeout


JavaScript function.


Navigate to your Vuex.Store instance and, after the mutations, add a new object of


actions. Inside, create a new function titled initializeShop:


const store = new Vuex.Store({
state: {
products: {}
},

mutations: {
products(state, payload) {
state.products = payload;
}
},

actions: {
initializeShop() {
}
}
});

With action parameters, the first parameter is the store itself, which we need to use in order


to utilize the mutations. There are two ways of doing this, the first is to use a single variable
and access its properties within the function. For example:


actions: {
initializeShop(store) {
store.commit('products');
}
}
Free download pdf