Event Handler Arguments
Part of the Fundamentals section of Coddy's Vue journey. Lesson 8 of 55.
A handler can receive different arguments from different buttons. Here the first button adds 3 and the second adds 8 to the same total.
const total = ref(0);
function add(amount) { total.value += amount; }
// <button @click="add(3)">Three</button>
// <button @click="add(8)">Eight</button>An expression inside @click runs when the event happens, so add(3) does not run during setup. A named handler keeps the calculation in JavaScript and makes multiple controls use one rule. Each click reads the current state.
Challenge
EasyBuild a scorekeeper. Start at 0, display the score in #result, and pass an amount to one award(points) handler: #small adds 2, #large adds 5.
Try it yourself
<!doctype html><html><head><meta charset="UTF-8"><title>Vue practice</title></head><body><div id="app"></div><script type="module" src="./main.js"></script></body></html>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
2Reactive State
Reactive RefsUpdating Refs in ScriptEvent Handler ArgumentsReactive ObjectsRecap: Reactive State5Conditions and Lists
Conditional BranchesShow without UnmountingRendering ListsStable List IdentityRecap: Conditions8Component Communication
Emitting EventsEvent PayloadsLifting Shared StateDefault and Named SlotsRecap: Shared Panel11Project: Community Board
Board StructureAdding Community Tasks