How to use methods in Vue

Using methods is fundamental for organizing component logic in Vue applications, providing a clean way to handle events and execute reusable functions. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented thousands of Vue methods across components for form handling, data manipulation, and user interactions in enterprise applications. From my expertise, the most effective approach is to define methods in the methods option with proper naming conventions. This method provides clear component organization, automatic this binding, and excellent debugging experience.

Define functions in the setup() function for handling events, calculations, and reusable component logic.

<template>
  <div>
    <p>Count: {{ count }}</p>
    <button @click="increment">+1</button>
    <button @click="() => incrementBy(5)">+5</button>
    <button @click="reset">Reset</button>
  </div>
</template>

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

const count = ref(0)

const increment = () => {
  count.value++
}

const incrementBy = (amount) => {
  count.value += amount
}

const reset = () => {
  count.value = 0
}
</script>

Functions in Vue Composition API are defined inside setup() and returned for template access. Use reactive references with .value for state modification. Functions can accept parameters and return values, providing flexible component logic. Use functions for actions and computed properties for derived data.

Best Practice Note:

This is the same approach we use in CoreUI Vue components for organizing component logic and handling user interactions.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author