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

Create a filters object within the ListPurchases component and create a function


inside titled currency(). This function accepts a single parameter of val and should


return the variable inside:


filters: {
currency(val) {
return val;
}
},

We can now use this function to manipulate the price integers. Add the filter to both the


unit and total price within the template:


<td>{{ product.variation.price | currency }}</td>
<td>{{ product.quantity }}</td>
<td>{{ product.variation.price * product.quantity | currency }}</td>

You won't notice anything in the browser, as we have yet to manipulate the value. Update


the function to ensure the number is fixed to two decimal places and has a $ preceding it:


filters: {
currency(val) {
return ' + val.toFixed(2);
}
},

Our prices are now nicely formatted and displaying correctly.


Calculating a total price


The next addition to our purchase list is a total value of the basket. This will need to be
calculated in a similar way to the basket count we did earlier.


Create a new computed function title: totalPrice. This function should loop through the


products and add the price up, taking into consideration any multiple quantities:


totalPrice() {
let total = 0;

for(let p of this.products) {
total += (p.variation.price * p.quantity);
}

return total;
}
Free download pdf