0
0
Vueframework~30 mins

Passing arguments to handlers in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Passing arguments to handlers
📖 Scenario: You are building a simple Vue 3 app where users can click buttons to greet different friends by name.
🎯 Goal: Create a Vue 3 component that shows three buttons labeled with friend names. When a button is clicked, it calls a handler function passing the friend's name as an argument. The handler then updates a message showing the greeting for that friend.
📋 What You'll Learn
Use Vue 3 Composition API with <script setup>
Create a reactive message variable to hold the greeting text
Create a handler function that accepts a name argument and updates the message
Add three buttons with friend names: 'Alice', 'Bob', and 'Charlie'
Pass the friend name as an argument to the click handler using @click
💡 Why This Matters
🌍 Real World
Passing arguments to event handlers is common in interactive web apps, like greeting users, selecting items, or filtering lists.
💼 Career
Understanding how to pass arguments to handlers is essential for building dynamic Vue components and handling user interactions effectively.
Progress0 / 4 steps
1
Set up the friend names array
Create a constant array called friends with these exact strings: 'Alice', 'Bob', and 'Charlie'.
Vue
Need a hint?

Use const friends = ['Alice', 'Bob', 'Charlie'] to create the array.

2
Create a reactive message variable
Import ref from 'vue' and create a reactive variable called message initialized to an empty string ''.
Vue
Need a hint?

Use import { ref } from 'vue' and then const message = ref('').

3
Write the greeting handler function
Create a function called greet that takes one argument name. Inside the function, set message.value to the string `Hello, ${name}!` using a template literal.
Vue
Need a hint?

Define function greet(name) and update message.value inside it.

4
Add buttons and bind click handlers
In the template, use a <button> inside a <template> that loops over friends with v-for. For each friend, create a button showing the friend's name. Add a @click event that calls greet(friend). Also add a <p> below the buttons that displays the reactive message.
Vue
Need a hint?

Use v-for="friend in friends" on buttons and @click="greet(friend)" to pass the name.