Method handlers and inline handlers let you respond to user actions in Vue. They help your app do things when buttons are clicked or keys pressed.
0
0
Method handlers vs inline handlers in Vue
Introduction
You want to run a simple action directly in the template, like toggling a value.
You need to run more complex logic or reuse code, so you put it in a method.
You want to keep your template clean and easy to read by using methods.
You want to pass parameters or handle events with extra processing.
You want to avoid repeating code by calling the same method from multiple places.
Syntax
Vue
<button @click="methodName">Click me</button> <button @click="inlineExpression">Click me</button>
Method handlers call a function defined in the methods section of your Vue component.
Inline handlers run simple JavaScript expressions directly inside the template.
Examples
This uses a method handler to show an alert when the button is clicked.
Vue
<template> <button @click="sayHello">Say Hello</button> </template> <script setup> function sayHello() { alert('Hello!') } </script>
This uses an inline handler to increase the count directly in the template.
Vue
<template> <button @click="count++">Increase Count</button> <p>Count: {{ count }}</p> </template> <script setup> import { ref } from 'vue' const count = ref(0) </script>
Method handler with a parameter passed from the template.
Vue
<template> <button @click="greet('Vue')">Greet Vue</button> </template> <script setup> function greet(name) { alert(`Hello, ${name}!`) } </script>
Inline handler doing a simple math operation directly in the template.
Vue
<template> <button @click="count = count + 1">Add One</button> <p>Count: {{ count }}</p> </template> <script setup> import { ref } from 'vue' const count = ref(0) </script>
Sample Program
This Vue component shows two buttons. One uses a method handler to increase the count. The other uses an inline handler. Both update the same count displayed below.
Vue
<template> <button @click="increment">Increment Method</button> <button @click="count++">Increment Inline</button> <p>Count: {{ count }}</p> </template> <script setup> import { ref } from 'vue' const count = ref(0) function increment() { count.value++ } </script>
OutputSuccess
Important Notes
Use method handlers for complex logic or when you want to reuse code.
Use inline handlers for simple, quick actions to keep your code short.
Too much logic in inline handlers can make templates hard to read.
Summary
Method handlers call functions defined in your Vue component.
Inline handlers run simple expressions directly in the template.
Choose method handlers for clarity and reuse; inline handlers for quick, simple actions.