TExcelTAD
Home › Vue › Vue Methods

Vue Methods

Methods are functions that belong to your component. You declare them in the methods option, and then use them in event handlers, in templates, or call them from other methods. Inside a method, this refers to the component instance, so you can read and change data with this.propertyName.

js
createApp({
  data() {
    return { count: 0 };
  },
  methods: {
    increment() {
      this.count++;
    }
  }
});

Methods as event handlers

The most common use: keep the template clean and move logic into named methods.

html · try it yourself
<style>
  .bulb { font-size: 60px; transition: filter .2s; }
  .off { filter: grayscale(1) brightness(.6); }
</style>

<div id="app">
  <div class="bulb" :class="{ off: !on }">💡</div>
  <button @click="toggle">Switch {{ on ? 'off' : 'on' }}</button>
  <p>Switched {{ switches }} time(s).</p>
</div>

<script type="module">
  import { createApp } from 'vue';

  createApp({
    data: () => ({ on: false, switches: 0 }),
    methods: {
      toggle() {
        this.on = !this.on;
        this.switches++;
        this.report();
      },
      report() {
        console.log(`The light is ${this.on ? 'on' : 'off'} (switch #${this.switches})`);
      }
    }
  }).mount('#app');
</script>

Notice that toggle calls another method with this.report().

Don't use arrow functions for methods

Arrow functions do not have their own this. If you write a method as an arrow function, this will not be the component, and this.count will fail.

js
methods: {
  increment: () => { this.count++ },   // ❌ `this` is not the component
  increment() { this.count++ }         // ✅ method shorthand
}

Arrow functions inside a method are fine — they reuse the method's this:

js
methods: {
  doubleAll() {
    this.numbers = this.numbers.map(n => n * 2);  // ✅
  }
}

Methods with arguments

html · try it yourself
<div id="app">
  <p>Cart total: <strong>{{ formatPrice(total) }}</strong></p>
  <ul>
    <li v-for="item in catalogue" :key="item.name">
      {{ item.name }} — {{ formatPrice(item.price) }}
      <button @click="addToCart(item)">Add</button>
    </li>
  </ul>
</div>

<script type="module">
  import { createApp } from 'vue';

  createApp({
    data: () => ({
      total: 0,
      catalogue: [
        { name: 'Notebook', price: 3.5 },
        { name: 'Pen', price: 1.25 },
        { name: 'Backpack', price: 29.9 }
      ]
    }),
    methods: {
      addToCart(item) {
        this.total += item.price;
        console.log('Added', item.name);
      },
      formatPrice(value) {
        return '
  

 + value.toFixed(2);
      }
    }
  }).mount('#app');
</script>

formatPrice is called inside the template to format values. Any method can be used in a template expression like this.

Methods in templates re-run on every render

A method called in the template runs again every time the component re-renders, even if its inputs did not change. Watch the log below: typing in the unrelated input re-renders the component, and the method runs again each time.

html · try it yourself
<div id="app">
  <input v-model="note" placeholder="Type here (unrelated data)">
  <p>Sum of 1..{{ n }} = {{ sumTo(n) }}</p>
  <button @click="n++">n + 1</button>
</div>

<script type="module">
  import { createApp } from 'vue';

  createApp({
    data: () => ({ n: 100, note: '' }),
    methods: {
      sumTo(n) {
        console.log('sumTo ran');
        let total = 0;
        for (let i = 1; i <= n; i++) total += i;
        return total;
      }
    }
  }).mount('#app');
</script>

For values derived from data, a computed property is usually better because it caches its result — you will learn it in the Computed Properties lesson.

Use a method when… Use a computed property when…
Responding to an event Deriving a value from other data
You need to pass arguments The value is used in several places
The result should be recalculated every time You want the result cached until its data changes

Methods in the Composition API

With setup(), methods are just plain functions that you return:

js
setup() {
  const count = ref(0);
  function increment() {
    count.value++;
  }
  return { count, increment };
}

No this is needed — the function closes over the count variable.

Tip: Name methods with verbs that describe the action — addToCart, toggleMenu, fetchUsers — so templates read like sentences: @click="addToCart(product)".

Note: Vue automatically binds this for every method in methods, so you can pass this.save as a callback (for example to setTimeout) without .bind(this).

Test yourself

Inside a method in the Options API, how do you change the data property score?

  1. score = 5
  2. this.score = 5
  3. data.score = 5
  4. $score = 5

Why should methods not be written as arrow functions?

  1. Arrow functions are slower
  2. Vue does not allow functions in methods
  3. Arrow functions have no own this, so they cannot reach the component
  4. Arrow functions cannot take arguments

How often does a method called inside the template run?

  1. Once, when the app starts
  2. Only when its arguments change
  3. Every time the component re-renders
  4. Never; methods only run for events