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

First, make a new property in the state object titled categories. This should be an object


by default:


state: {
products: {},
categories: {}
}

Next, create a new mutation called categories. Along with the state, this should take a


second parameter. To be consistent, title it payload – as this is what Vuex refers to it as:


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

categories(state, payload) {
}
},

Now for the functionality. This mutation needs to loop through the products. For every


product, it needs to isolate the type. Once it has the title and slug, it needs to check if an


entry exists with that slug; if it does, append the product handle to the products array, if


not – it needs to create a new array and details.


Create an empty categories object and loop through the payload, setting a variable for


both the product and type:


categories(state, payload) {
let categories = {};

Object.keys(payload).forEach(key => {
let product = payload[key],
type = product.type;
});
}

We now need to check if an entry exists with the key of the current type.handle. If it does


not, we need to create a new entry with it. The entry needs to have the title, handle, and an


empty products array:


categories(state, payload) {
let categories = {};

Object.keys(payload).forEach(key => {
let product = payload[key],
type = product.type;
Free download pdf