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

However, with ES2015, we are able to use argument destructuring and utilize the


properties we need. For this action, we only need the commit function, like so:


actions: {
initializeShop({commit}) {
commit('products');
}
}

If we wanted the state from the store as well, we could add it to the curly brackets:


actions: {
initializeShop({state, commit}) {
commit('products');
// state.products
}
}

Using this "exploded" method of accessing the properties makes our code cleaner and less


repetitive. Remove the state property and add a second parameter after the curly brackets


labeled products. This will be our formatted product's data. Pass that variable directly to


the product's commit function:


initializeShop({commit}, products) {
commit('products', products);
}

Using actions is as simple as using mutations, except instead of using $store.commit,


you use $store.dispatch. Update your created method – not forgetting to change the


function name too, and check your app still works:


created() {
CSV.fetch({url: './data/csv-files/bicycles.csv'}).then(data => {
this.$store.dispatch('initializeShop', this.$formatProducts(data));
});
}

The next step is to create a mutation for our categories. As we may want to update our
categories independently of our products – we should create a second function within the


mutations. It should also be this function that loops through the products and creates the


list of categories.

Free download pdf