Getting Started with Vue.js Chapter 1
We could, alternatively, create a method titled shirtCost that does the same as our
computed function; however, it's better to practice to use computed in this case.
This is because computed functions are cached, whereas method functions are not. If you
imagine our methods being a lot more complicated than they currently are, calling function
after function repeatedly (for example, if we wanted to display the price in several
locations) could have a performance impact. With computed functions, as long as the data
does not change, you can call it as many times as you want, with the result being cached by
the application. If the data does change, it only needs to recalculate once, and re-cache that
result.
Make a computed function for both the shirtPrice and hatPrice, so that both variables
can be used in the view. Don't forget that to call the functions internally you must use
the this variable - for example, this.addCurrency(). Use the following HTML code as
the template for your view:
<div id="app">
<p>The shirt costs {{ shirtCost }}</p>
<p>The hat costs {{ hatCost }}</p>
</div>
Have a go at creating the computed functions yourself before comparing against the
following code. Don't forget that there are many ways to do things in development, so don't
worry if your code works but doesn't match the following example:
const app = new Vue({
el: '#app',
data: {
shirtPrice: 25,
hatPrice: 10,
currency: '$',
salesTax: 16
},
computed: {
shirtCost() {
returnthis.addCurrency(this.calculateSalesTax(
this.shirtPrice))
},
hatCost() {
return this.addCurrency(this.calculateSalesTax(
this.hatPrice))
},
},
methods: {
calculateSalesTax(price) {