Explain Codes LogoExplain Codes Logo

Vue: How do I call multiple functions with @click?

javascript
event-handling
vuejs
function-calls
Alex KataevbyAlex Kataev·Mar 10, 2025
TLDR

Quickly execute multiple functions in Vue on a single @click by chain calling methods with semicolons or by grouping them in a single method.

<button @click="firstTask(); secondTask();">Click Me</button> // OR <button @click="taskHandler">Click Me</button>
methods: { taskHandler() { this.firstTask(); this.secondTask(); }, firstTask() { // ... Task 1: Save the world! ... }, secondTask() { // ... Task 2: Make some coffee ... } }

The basics of multi-function calls in Vue

In Vue 2.3 or higher, running multiple functions as a response to a single event is feasible using semicolon-separated syntax. You can use @click or v-on:click for this purpose, with the latter just being the full form of @click.

However, make sure to keep your code organized. Instead of stuffing several functions inside an event, pack them inside a single method in your Vue instance's methods property.

Sequential and conditional methods execution

Use an array of functions or an immediate function to handle the timing and conditional statements within multiple function calls.

<button @click="runAllTasks">Click Me</button>
methods: { runAllTasks() { [this.firstTask, this.secondTask].forEach(func => func()); // "Hey tasks, line up. One by one!" } }

Integrate conditional logic within the handler to control which functions are triggered when needing only certain functions to execute.

Battle of the @click and v-on:click

While Vue lets you use either v-on:click or @click for event handling, favor @click for its shorter syntax and better readability. They essentially mean the same thing, and it’s up to personal preference and your project’s style guide.

Error handling in multi-function calls

In chaining or grouping multiple function calls, it's important to consider error handling strategies. This stop errors from one function from blocking the others.

methods: { executeTasksSafely() { try { this.firstTask(); } catch (error) { console.error('firstTask had an "Oopsie" moment', error); } try { this.secondTask(); } catch (error) { console.error('secondTask faced a "Well, that happened" scenario', error); } } }

Remember, a try-catch block is your best friend when error handling!

Keep it simple and neat with IIFEs

For simpler tasks or quick prototyping, Immediately Invoked Function Expressions (IIFE) are a handy alternative.

<button @click="(function() { console.log('Hello'); alert('World!'); })()"> Say Hello </button>

Although this can keep your HTML clean, avoid using IIFEs for complex logic or production use due to reasons of maintainability and debugging.

Best Practices Summary

  • Clear Method Names: Make your function names descriptive.
  • Function Purpose: Keep each function focused on a single task.
  • Avoid Side Effects: Keep your functions pure. This improves testability.