Vue Methods

Vue Tutorial

🧠 Vue Methods

In Vue.js, Vue Methods are functions defined inside a Vue component that are used to handle events, perform actions, and execute logic when something happens in the UI.

 What are Vue Methods?

Vue methods are regular JavaScript functions that:

  • Respond to events (click, submit, keyup, etc.)

  • Perform calculations

  • Update data

  • Execute business logic

They are defined inside the methods option of a Vue app or component.


 Basic Syntax

methods: {
methodName() {
// logic here
}
}

 Example 1: Simple Method

<div id="app">
<button @click="sayHello">Click Me</button>
</div>
<script>
const app = Vue.createApp({
methods: {
sayHello() {
alert(“Hello Vue!”)
}
}
})
app.mount(“#app”)
</script>

📌 The method runs when the button is clicked.


 Example 2: Method with Data

<div id="app">
<button @click="increase">+</button>
<p>Count: {{ count }}</p>
</div>
data() {
return {
count: 0
}
},
methods: {
increase() {
this.count++
}
}

✔ Methods can modify reactive data using this.


 Example 3: Passing Parameters

<button @click="greet('Sanjit')">Greet</button>
methods: {
greet(name) {
alert("Welcome " + name)
}
}

 Example 4: Using $event

<button @click="showEvent($event)">Click</button>
methods: {
showEvent(event) {
console.log(event.type)
}
}

📌 $event gives access to the native DOM event.


 Example 5: Methods in Template Expressions

<p>{{ getMessage() }}</p>
methods: {
getMessage() {
return "Hello from Method"
}
}

⚠️ This method runs every time the component re-renders.


 Methods vs Computed Properties (Very Important ⚠️)

Feature Methods Computed
Execution Every render Cached
Performance Lower Higher
Use for Actions / events Calculated data
Parameters Yes No

✔ Use methods for:

  • Click handlers

  • API calls

  • Form submission

✔ Use computed for:

  • Derived data

  • Filtering

  • Calculations based on state


 Methods with Forms

<form @submit.prevent="submitForm">
<input v-model="name">
<button>Submit</button>
</form>
methods: {
submitForm() {
alert(this.name)
}
}

 Calling Methods from Another Method

methods: {
first() {
this.second()
},
second() {
console.log("Second method")
}
}

 Common Mistakes ❌

❌ Using arrow functions:

methods: {
myMethod: () => {
console.log(this) // wrong
}
}

✔ Correct:

myMethod() {
console.log(this)
}

 Best Practices ✅

✔ Keep methods simple and readable
✔ Use clear names (handleSubmit, incrementCount)
✔ Avoid heavy logic in templates
✔ Prefer computed for repeated calculations


 Summary Table

Task Use
Handle click Method
Submit form Method
Update data Method
Derived value Computed
Event logic Method

 Conclusion

Vue methods are the action handlers of your application.
They connect user interaction with application logic and are essential for building interactive Vue apps.

You may also like...