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 - Adding a Checkout Chapter 11

variationTitle: item.variantTitle(item.variation),
variation: item.variation,
quantity: 1
});
}

If it matches, we can increment the quantity by one on that object, using the ++ notation in


JavaScript. If not, we can add the new object to the basket array. When using the find


function, we can return the product if it exists. If not, we can add a new item:


addToBasket(state, item) {
let product = state.basket.find(p => {
if(p.sku == item.variation.sku) {
p.quantity++;

return p;
}
});

if(!product) {
state.basket.push({
sku: item.variation.sku,
title: item.product.title,
handle: item.slug,
image: item.image,
variationTitle: item.variantTitle(item.variation),
variation: item.variation,
quantity: 1
});
}
}

We now have a basket being populated as the item is added to the basket, and


incrementing when it exists already.


To improve the usability of the app, we should give the user some feedback when they


have added an item to the basket. This can be done by updating the Add to Basket button


briefly and showing a product count with a link to the basket in the header of the site.

Free download pdf