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

If our header were to feature more items than our cart link, it would be advisable to


abstract it out into a separate component to keep the methods, layout, and functions
contained. However, as it is only going to feature this one link in our example app, adding


the function to the Vue instance will suffice.


Create a new getter in the store titled cartQuantity. As a placeholder, return 1. The


state will be required to calculate the quantity, so ensure that is passed into the function


for now:


getters: {

cartQuantity: (state) => {
return 1;
}
}

Head back to your Vue instance and return the result of the getter. Ideally, we want to show


the count of the basket in brackets, but we only want to show the brackets if there are


items. Within the computed function, check the result of this getter and output the result
with brackets if the result exists:


cartQuantity() {
const quantity = this.$store.getters.cartQuantity;
return quantity? `(${quantity})` : '';
}

Changing the result within the Vuex getter should reveal either the number in brackets or


nothing at all.


Calculating the basket quantity


With the display logic in place, we can now proceed with calculating how many items are


in the basket. We could count the number of items in the basket array, however, this will


only tell us how many different products are there now and not if the same product was


added many times.

Free download pdf