Vue Methods
The methods option defines reusable functions on a component that can be invoked from templates, event handlers, or from other methods.
Defining Methods
The methods option is an object where every property is a function. Inside a method, this refers to the component instance, giving direct access to everything in data, computed properties, and other methods. Methods are the natural home for anything that changes state or performs an action in response to user input.
A method that updates data
<div id="app">
<p>Count: {{ count }}</p>
<button @click="increment">Increment</button>
</div>
<script>
const app = Vue.createApp({
data() {
return { count: 0 }
},
methods: {
increment() {
this.count += 1
}
}
})
app.mount('#app')
</script>Calling Methods from Templates
Methods can be called two ways in a template: as an event handler, shown above, or directly inside a text interpolation or attribute binding when you need a computed-looking value on demand. When called this way, the method re-runs on every re-render, so it should stay lightweight and side-effect free.
Calling a method inside an interpolation
<div id="app">
<p>{{ fullName() }}</p>
<button @click="swapNames">Swap first and last</button>
</div>
<script>
const app = Vue.createApp({
data() {
return { first: 'Ada', last: 'Lovelace' }
},
methods: {
fullName() {
return this.first + ' ' + this.last
},
swapNames() {
const temp = this.first
this.first = this.last
this.last = temp
}
}
})
app.mount('#app')
</script>- Always use a regular function shorthand (methodName() {}) inside methods, never an arrow function, so this binds correctly.
- Methods can call other methods on the same instance using this.otherMethod().
- A method invoked in a template re-executes every time the component re-renders.
- Methods are the right place for anything with side effects: mutating data, making a request, emitting an event.
- Passing arguments works the same in a method call from the template as it does in plain JavaScript.
Methods vs. Computed Properties
Methods and computed properties can look interchangeable in a template, but they behave very differently under the hood. A computed property caches its result and only recalculates when one of its reactive dependencies changes. A method has no cache: it reruns in full every single time the component re-renders, regardless of whether anything relevant actually changed.
A method that also calls another method
<div id="app">
<p>{{ status() }}</p>
<button @click="toggle">Toggle status</button>
</div>
<script>
const app = Vue.createApp({
data() {
return { isOnline: false }
},
methods: {
toggle() {
this.isOnline = !this.isOnline
this.logChange()
},
logChange() {
console.log('Status changed to', this.isOnline)
},
status() {
return this.isOnline ? 'Online' : 'Offline'
}
}
})
app.mount('#app')
</script>Exercise: Vue Methods
Where are component methods defined when using the Options API?