Complete Vue.js 2 Web Development_ Practical guide to building end-to-end web development solutions with Vue.js 2

(singke) #1
Getting Started with Vue.js Chapter 1

Computed functions are not just limited to basic functionality - remember, they are


designed to remove all logic and manipulations from the view. A more complex example
might be the following:


const app = new Vue({
el: '#app',
data: {
price: 25,
currency: '$',
salesTax: 16
},
computed: {
cost() {
// Work out the price of the item including
salesTax
let itemCost = parseFloat(
Math.round((this.salesTax / 100) *
this.price) + this.price).toFixed(2);
// Add text before displaying the currency and
amount
let output = 'This item costs ' +
this.currency + itemCost;
// Append to the output variable the price
without salesTax
output += ' (' + this.currency + this.price +
' excluding salesTax)';
// Return the output value
return output;
}
}
});

Although this might seem advanced at first glance, the code is taking a fixed price and
calculating what it would be with sales tax added. The price, salesTax, and currency


symbol are all stored as values on the data object and accessed within the cost()


computed function. The view outputs {{ cost }}, which produces the following:


This item costs $29.00 ($25 excluding sales tax)


Computed functions will recalculate and update if any data is updated, by either the user
or the application itself. This allows for our function to dynamically update based on the


price and salesTax values. Try one of the following commands in the console in your


browser:


app.salesTax = 20

app.price = 99.99
Free download pdf