Vue Methods

up:: Vue

Note

Use primarily for event binding or data binding. Method is executed for every “re-render” cycle of the component. Use for events or data really needs to be re-evaluated all the time.

On the createApp function, you can set methods which are JavaScript functions.

const app = Vue.createApp({
methods: {
	outputStr() {
		const randomNo = Math.random();
		if (randomNo < 0.5) {
			return "Learn Vue";
		} else {
			return "Master Vue";
		}
	}
}
})

You can then call those in the html template

<p>{{ outputStr() }}</p>

or simply point at it (this is preferred):

<p>{{ outputStr() }}</p>

Using data in methods

When you want to use data defined in the data() property on Vue, you need to call it with the this keyword.

const app = Vue.createApp({
data() {
	return {
		greetingA: "G'day!",
		greetingB: "Hello there!"
	}
}
methods: {
	outputStr() {
		const randomNo = Math.random();
		if (randomNo < 0.5) {
			return this.greetingA;
		} else {
			return this.greetingB;
		}
	}
}
})

Warning

However, dynamic properties (returning data from a method) is not the best. Whenever something on the page changes, all methods are re-evaluated. This is not good from a performance standpoint. Instead, it is better to use Vue Computed Properties