0
0
Vueframework~5 mins

Passing arguments to handlers in Vue

Choose your learning style9 modes available
Introduction

Passing arguments to handlers lets you send extra information when a user interacts with your app. This helps your app respond in different ways based on what you send.

You want to know which button was clicked in a list of buttons.
You need to send a specific value when a user clicks a button.
You want to pass extra data to a function when an event happens.
You want to reuse one handler but with different inputs.
Syntax
Vue
<button @click="handlerName(argument)">Click me</button>
Use parentheses to call the handler with arguments inside the template.
You can pass variables, strings, numbers, or even event objects.
Examples
This calls sayHello with the string 'Alice' when clicked.
Vue
<button @click="sayHello('Alice')">Greet Alice</button>
This calls incrementCount with the number 5.
Vue
<button @click="incrementCount(5)">Add 5</button>
This passes the event object and a string 'extra' to the handler.
Vue
<button @click="handleClick($event, 'extra')">Click me</button>
Sample Program

This Vue component has two buttons. Each button calls the greet function with a different name. When clicked, the message below changes to greet that person.

Vue
<template>
  <button @click="greet('Bob')">Say Hello to Bob</button>
  <button @click="greet('Carol')">Say Hello to Carol</button>
  <p>{{ message }}</p>
</template>

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

const message = ref('')

function greet(name) {
  message.value = `Hello, ${name}!` // Show greeting with the passed name
}
</script>
OutputSuccess
Important Notes

If you want to access the event object along with arguments, include $event as a parameter.

Do not call the handler without a function wrapper if you want to pass arguments; otherwise, it runs immediately.

Summary

Passing arguments lets you customize what your handler does based on input.

Use parentheses in the template to send arguments.

You can pass strings, numbers, variables, or the event object.