Methods and Event Handling

⚙️ 1. What Are Methods?

In Vue, methods are regular JavaScript functions you define inside the component.
They are used for logic, event handling, and manipulating data — but unlike computed properties, they do not cache results.


✅ Example: Basic Methods

<template>
  <div>
    <p>Count: {{ count }}</p>
    <button @click="increment">+</button>
    <button @click="decrement"></button>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const count = ref(0)

function increment() {
  count.value++
}

function decrement() {
  count.value--
}
</script>

🧠 Explanation:

  • We define two methods: increment() and decrement().
  • The @click directive (short for v-on:click) binds these functions to the buttons.
  • Each click updates the count variable.

🖱️ 2. Event Handling

Vue makes it easy to listen to and handle DOM events using v-on or the @ shorthand.


✅ Example: Listening to Events

<button @click="sayHello">Click Me</button>

<script setup>
function sayHello() {
  alert('Hello from Vue!')
}
</script>

✅ Example: Inline Handlers

You can run expressions directly in templates:

<button @click="count++">Clicked {{ count }} times</button>

⚠️ Keep expressions simple — complex logic belongs in methods.


🎯 3. Passing Arguments to Methods

You can pass arguments just like normal JavaScript function calls.

✅ Example:

<template>
  <button @click="greet('Vue Learner')">Greet</button>
</template>

<script setup>
function greet(name) {
  alert(`Hello, ${name}!`)
}
</script>

🧩 4. Using Event Objects

When you need access to the DOM event, use $event or include the event parameter directly.

✅ Example:

<template>
  <input @input="handleInput($event)">
</template>

<script setup>
function handleInput(event) {
  console.log('User typed:', event.target.value)
}
</script>

or simpler:

<input @input="(e) => console.log(e.target.value)">

🧠 5. Event Modifiers

Vue offers modifiers to simplify common event handling cases:

ModifierPurpose
.stopStop event propagation
.preventPrevent default browser behavior
.onceRun handler only once
.captureUse capture mode
.selfTrigger only if event target is the element itself
.passiveImproves scroll performance

✅ Example: Event Modifiers in Action

<!-- Prevent form from reloading page -->
<form @submit.prevent="handleSubmit">
  <input v-model="name" placeholder="Your name">
  <button type="submit">Submit</button>
</form>

<script setup>
import { ref } from 'vue'
const name = ref('')

function handleSubmit() {
  alert(`Hello, ${name.value}!`)
}
</script>

🧩 @submit.prevent → automatically runs event.preventDefault()
(no need to write it manually)


🧱 6. Key Modifiers (for Keyboard Events)

You can listen for specific keys using modifiers.

✅ Example:

<input @keyup.enter="saveTask" placeholder="Press Enter to save">

<script setup>
function saveTask() {
  alert('Task saved!')
}
</script>

Other examples:

  • .enter → Enter key
  • .esc → Escape key
  • .space → Spacebar
  • .tab, .delete, .up, .down, etc.

⚡ 7. Mouse Modifiers (for Clicks)

You can also filter clicks by mouse button:

ModifierDescription
.leftLeft click
.rightRight click
.middleMiddle click
<button @click.right.prevent="showContextMenu">Right-click me</button>

🧩 Summary Table

FeatureDescriptionExample
MethodsFunctions defined in a componentfunction greet() { ... }
Event BindingUse v-on / @ to bind@click="greet"
Inline ExpressionRun small expressions@click="count++"
Event ModifiersSimplify common event behaviors@submit.prevent
Key ModifiersTrigger events on key press@keyup.enter="save"

Leave a Reply