Vue — Methods
Inline handlers
<template>
<div>
<button @click="count++">Add 1</button>
<p>Count: {{ count }}</p>
</div>
</template>
<script>
export default {
data() {
return { count: 0 }
}
}
</script>
Method handlers
<template>
<div>
<button @click="increment">Add 1</button>
<button @click="add(5)">Add 5</button>
</div>
</template>
<script>
export default {
data() {
return { count: 0 }
},
methods: {
increment() {
this.count++
},
add(amount) {
this.count += amount
}
}
}
</script>
Event object
<button @click="handleClick">Click</button>
methods: {
handleClick(event) {
console.log(event.target) // Element
console.log(event.type) // "click"
}
}
Event modifiers
<!-- Prevent default -->
<form @submit.prevent="onSubmit">Submit</form>
<!-- Stop propagation -->
<button @click.stop="handleClick">Click</button>
<!-- Only trigger once -->
<button @click.once="handleClick">Click once</button>
<!-- Self only -->
<div @click.self="handleClick">Self</div>
<!-- Capture -->
<div @click.capture="handleClick">Capture</div>
Key modifiers
<input @keyup.enter="submit">
<input @keyup.esc="cancel">
<input @keyup.ctrl.s="save">
<input @keyup.shift.enter="newline">
Mouse modifiers
<div @click.ctrl="handleClick">Ctrl + Click</div>
<div @click.left="handleLeft">Left Click</div>
<div @click.right="handleRight">Right Click</div>
<div @click.middle="handleMiddle">Middle Click</div>
Mini Practice
- Create click handlers
- Pass arguments to methods
- Use event modifiers
- Handle keyboard events
Up Next
Continue with Computed Properties - Derived state.
Related Topics
Frequently Asked Questions about Methods
What is Methods in Vue?
Methods is a fundamental concept in Vue. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Methods?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Methods.
Why is Methods important in Vue?
Methods is essential for Vue development. Understanding this concept will help you write better code and solve real-world problems more effectively.