VueJS can automatically bind the this
value for functions inside the methods
object and make them always refer to the component instance. This will ensure that a method retains the correct this
value if it is being used as an event listener or callback. Let us go through some simple examples to call method in VueJS 3.
Arrows should not be used while defining methods in VueJS as this will prevent the framework to bind the correct this
value. To use methods in VueJS for a component instance, you need to use the methods
option. The option will be an object containing different required methods.
Create a new method in methods
You will first have to define a new method using the methods
option as shown below.
export default {
methods: {
demoMethod() {
alert('Hello World')
}
},
}
1. Call method in VueJS template
As shown below, you can make the method call in a VueJS template file. So, on a button click, the method will be called.
<template>
<button @click="demoMethod()">Click here</button>
</template>
export default {
methods: {
demoMethod() {
alert('Hello World')
}
},
}
2. Call a method from mounted
You can call a method using a mounted()
lifecycle hook. This will trigger the method operation, whenever the page loads. Recommended for methods that hold code that should work right after a page loads. You should use the this
keyword before the method to call it in mounted()
, as shown below.
export default {
methods: {
demoMethod() {
alert('Hello World')
}
},
mounted() {
this.demoMethod()
}
}
3. Call a method from another method
In case you have multiple methods defined in the methods
object. You can also call one method from another, as shown below.
However, since these methods are called outside VueJS template, make use of the this keyword to call the method.
export default {
methods: {
demoMethod() {
alert('Hello World 1')
this.methodNew()
}
methodNew(){
alert('Hello World 2')
}
},
mounted() {
this.demoMethod()
}
}