Vue Methods
Methods are functions that belong to your component. You declare them in the methods option, and then use them in event handlers, in templates, or call them from other methods. Inside a method, this refers to the component instance, so you can read and change data with this.propertyName.
js
createApp({
data() {
return { count: 0 };
},
methods: {
increment() {
this.count++;
}
}
});Methods as event handlers
The most common use: keep the template clean and move logic into named methods.
html · try it yourself
<style>
.bulb { font-size: 60px; transition: filter .2s; }
.off { filter: grayscale(1) brightness(.6); }
</style>
<div id="app">
<div class="bulb" :class="{ off: !on }">💡</div>
<button @click="toggle">Switch {{ on ? 'off' : 'on' }}</button>
<p>Switched {{ switches }} time(s).</p>
</div>
<script type="module">
import { createApp } from 'vue';
createApp({
data: () => ({ on: false, switches: 0 }),
methods: {
toggle() {
this.on = !this.on;
this.switches++;
this.report();
},
report() {
console.log(`The light is ${this.on ? 'on' : 'off'} (switch #${this.switches})`);
}
}
}).mount('#app');
</script>Notice that toggle calls another method with this.report().
Don't use arrow functions for methods
Arrow functions do not have their own this. If you write a method as an arrow function, this will not be the component, and this.count will fail.
js
methods: {
increment: () => { this.count++ }, // ❌ `this` is not the component
increment() { this.count++ } // ✅ method shorthand
}Arrow functions inside a method are fine — they reuse the method's this:
js
methods: {
doubleAll() {
this.numbers = this.numbers.map(n => n * 2); // ✅
}
}Methods with arguments
html · try it yourself
<div id="app">
<p>Cart total: <strong>{{ formatPrice(total) }}</strong></p>
<ul>
<li v-for="item in catalogue" :key="item.name">
{{ item.name }} — {{ formatPrice(item.price) }}
<button @click="addToCart(item)">Add</button>
</li>
</ul>
</div>
<script type="module">
import { createApp } from 'vue';
createApp({
data: () => ({
total: 0,
catalogue: [
{ name: 'Notebook', price: 3.5 },
{ name: 'Pen', price: 1.25 },
{ name: 'Backpack', price: 29.9 }
]
}),
methods: {
addToCart(item) {
this.total += item.price;
console.log('Added', item.name);
},
formatPrice(value) {
return '