Getting Started with Vue.js Chapter 1
The paragraph and prices will update instantly. This is because computed functions are
reactive to the data object and the rest of the application.
Methods and reusable functions
Within your Vue application, you may wish to calculate or manipulate data in a consistent
or repetitive way or run tasks that require no output to your view. For example, if you
wanted to calculate the sales tax on every price or retrieve some data from an API before
assigning it to some variables.
Rather than creating computed functions for each time, we need to do this, Vue allows you
to create functions or methods. These get declared in your application and can be accessed
from anywhere - similar to the data or computed functions.
Add a method object to your Vue application and note the updates to the data object:
const app = new Vue({
el: '#app',
data: {
shirtPrice: 25,
hatPrice: 10,
currency: '$',
salesTax: 16
},
methods: {
}
});
Within the data object, the price key has been replaced with two prices - shirtPrice
and hatPrice. We'll create a method to calculate the sales tax for each of these prices.
Similar to creating a function for the computed object, create a method function title
called calculateSalesTax. This function needs to accept a single parameter, which will
be the price. Inside, we will use the code from the previous example to calculate the sales
tax. Remember to replace this.price with just the parameter name: price, as shown
here:
methods: {
calculateSalesTax(price) {
// Work out the price of the item including
sales tax
return parseFloat(
Math.round((this.salesTax / 100) * price)
+ price).toFixed(2);