Methods
The logic for many event handlers will be too complex to keep inside the v-on
directive. It is often more practical to bind or invoke a method from the Vue instance.
All methods are placed inside of the methods
property of the Vue instance. When inside a method, the this
keyword must be used to access data properties.
const app = Vue.createApp({
data: function () {
return { name: 'John' }
},
methods: {
greeting: function () {
// the this keyword is used access the data object
if (this.name) {
alert(`Hello ${this.name}`)
} else {
alert('Hello Friend.')
}
}
}
})
const vm = app.mount('#app')
Binding Methods
To bind a method to a v-on
directive, provide the method's name as the value.
<div id="app">
<button v-on:click="greeting">Say Hello</button>
</div>
Invoking Methods
Instead of the binding methods directly, the v-on
directive will also allow you to invoke methods as an inline JavaScript statement.
Invoking a method makes it possible to pass arguments, allowing for methods to be more flexible.
const app = Vue.createApp({
data: function () {
return { name: 'John' }
},
methods: {
greeting: function (name) {
if (name) {
alert(`Hello ${name}`)
} else if (this.name) {
alert(`Hello ${this.name}`)
} else {
alert('Hello Friend.')
}
}
}
})
const vm = app.mount('#app')
<div id="app">
<button v-on:click="greeting('Jim')">Say Hello</button>
</div>
Event Object
When working with events, it is sometimes necessary to have direct access to the event object. Vue makes that possible by using the $event
variable as an argument of the invoked method.
const app = Vue.createApp({
el: `#app`,
data: function () {
return { name: 'John' }
},
methods: {
greeting: function (name, event) {
if (name) {
alert(`Hello ${name}`)
} else if (this.name) {
alert(`Hello ${this.name}`)
} else {
alert('Hello Friend.')
}
alert(event.type)
}
}
})
const vm = app.mount('#app')
<div id="app">
<button v-on:click="greeting('Jim', $event)">Say Hello</button>
</div>