Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

Vue Tutorial

Vue HOME Vue Intro Vue Directives Vue v-bind Vue v-if Vue v-show Vue v-for Vue Events Vue v-on Vue Methods Vue Event Modifiers Vue Forms Vue v-model Vue CSS Binding Vue Computed Properties Vue Watchers Vue Templates

Scaling Up

Vue Why, How and Setup Vue First SFC Page Vue Components Vue Props Vue v-for Components Vue $emit() Vue Fallthrough Attributes Vue Scoped Styling Vue Local Components Vue Slots Vue v-slot Vue Scoped Slots Vue Dynamic Components Vue Teleport Vue HTTP Request Vue Template Refs Vue Lifecycle Hooks Vue Provide/Inject Vue Routing Vue Form Inputs Vue Animations Vue Animations with v-for Vue Build Vue Composition API

Vue Reference

Vue Built-in Attributes Vue Built-in Components Vue Built-in Elements Vue Component Instance Vue Directives Vue Instance Options Vue Lifecycle Hooks

Vue Examples

Vue Examples Vue Exercises Vue Quiz Vue Syllabus Vue Study Plan Vue Server Vue Certificate

Vue Methods

Vue methods are functions that belong to the Vue instance under the 'methods' property.

Vue methods are great to use with event handling (v-on) to do more complex things.

Vue methods can also be used to do other things than event handling.

The Vue 'methods' Property

We have already used one Vue property in this tutorial, the 'data' property, where we can store values.

There is another Vue property called 'methods' where we can store functions that belong to the Vue instance. A method can be stored in the Vue instance like this:

const app = Vue.createApp({
  data() {
    return {
      text: ''
    }
  },
  methods: {
    writeText() {
      this.text = 'Hello World!'
    }
  }
})

Tip: We need to write this. as prefix to refer to a data property from inside a method.

To call the 'writeText' method when we click the <div> element we can write the code below:

<div v-on:click="writeText"></div>

The example looks like this:

Example

The v-on directive is used on the <div> element to listen to the 'click' event. When the 'click' event occurs the 'writeText' method is called and the text is changed.

<div id="app">
  <p>Click on the box below:</p>
  <div v-on:click="writeText">
    {{ text }}
  </div>
</div>

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
  const app = Vue.createApp({
    data() {
      return {
        text: ''
      }
    },
    methods: {
      writeText() {
        this.text = 'Hello World!'
      }
    }
  })
  app.mount('#app')
</script>
Try it Yourself »

Call a Method with the Event Object

When an event occurs so that a method is called, the event object is passed with the method by default. This is very convenient because the event object contains a lot of useful data, like for example the target object, the event type, or the mouse position when the 'click' or 'mousemove' event occurred.

Example

The v-on directive is used on the <div> element to listen to the 'mousemove' event. When the 'mousemove' event occurs the 'mousePos' method is called and the event object is sent with the method by default so we can get the mouse pointer position.

We must use the this. prefix to refer to "xPos" inside the Vue instance data property from the method.

<div id="app">
  <p>Move the mouse pointer over the box below:</p>
  <div v-on:mousemove="mousePos"></div>
</div>

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
  const app = Vue.createApp({
    data() {
      return {
        xPos: 0,
        yPos: 0
      }
    },
    methods: {
      mousePos(event) {
        this.xPos = event.offsetX
        this.yPos = event.offsetY
      }
    }
  })
  app.mount('#app')
</script>
Try it Yourself »

If we expand the example above by just one line, we can also make the background color change based on the mouse pointer position in the x-direction. The only thing we need to add is v-bind to change the background-color in the style attribute:

Example

The difference here from the example above is that the background color is bound to 'xPos' with v-bind so that hsl 'hue' value is set equal to 'xPos'.

<div
  v-on:mousemove="mousePos"
  v-bind:style="{backgroundColor:'hsl('+xPos+',80%,80%)'}">
</div>
Try it Yourself »

In the example below the event object carries a text from the <textarea> tag to make it look like we are writing inside a notebook.

Example

The v-on directive is used on the <textarea> tag to listen to the 'input' event which occurs whenever there is a change in the text inside the textarea element.

When the 'input' event occurs the 'writeText' method is called and the event object is sent with the method by default so we can get the text from the <textarea> tag. The 'text' property in the Vue instance is updated by the 'writeText' method. A span element is set up to show the 'text' value with the double curly braces syntax, and this is updated automatically by Vue.

<div id="app">
  <textarea v-on:input="writeText" placeholder="Start writing.."></textarea>
  <span>{{ text }}</span>
</div>

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
  const app = Vue.createApp({
    data() {
      return {
        text: ''
      }
    },
    methods: {
      writeText(event) {
        this.text = event.target.value
      }
    }
  })
  app.mount('#app')
</script>
Try it Yourself »

Passing Arguments

Sometimes we want to pass an argument with the method when an event occurs.

Lets say you work as a forest ranger, and you want to keep count of moose sightings. Sometimes one or two moose are seen, other times over 10 moose might be seen during a day. We add buttons to count sightings '+1' and '+5', and a '-1' button in case we have counted too many.

In this case we can use the same method for all three buttons, and just call the method with a different number as an argument from the different buttons. This is how we can call a method with an argument:

<button v-on:click="addMoose(5)">+5</button>

And this is how the 'addMoose' method looks like:

methods: {
  addMoose(number) {
    this.count = this.count + number
  }
}

Lets see how passing an argument with a method works in a full example.

Example

<div id="app">
  <img src="img_moose.jpg">
  <p>{{ "Moose count: " + count }}</p>
  <button v-on:click="addMoose(+1)">+1</button>
  <button v-on:click="addMoose(+5)">+5</button>
  <button v-on:click="addMoose(-1)">-1</button>
</div>

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
  const app = Vue.createApp({
    data() {
      return {
        count: 0
      }
    },
    methods: {
      addMoose(number) {
        this.count+=number
      }
    }
  })
 app.mount('#app')
</script>
Try it Yourself »

Passing both an Argument and The Event Object

If we want to pass both the event object and another argument, there is a reserved name '$event' we can use where the method is called, like this:

<button v-on:click="addAnimal($event, 5)">+5</button>

And this is how the method in the Vue instance looks like:

methods: {
  addAnimal(e, number) {
    if(e.target.parentElement.id==="tigers"){
      this.tigers = this.tigers + number
    }
  }
}

Now let us look at an example to see how to pass both the event object and another argument with a method.

Example

In this example our method receives both the event object and a text.

<div id="app">
  <img
    src="img_tiger.jpg"
    id="tiger"
    v-on:click="myMethod($event,'Hello')">
  <p>"{{ msgAndId }}"</p>
</div>

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
  const app = Vue.createApp({
    data() {
      return {
        msgAndId: ''
      }
    },
    methods: {
      myMethod(e,msg) {
        this.msgAndId = msg + ', '
        this.msgAndId += e.target.id
      }
    }
  })
 app.mount('#app')
</script>
Try it Yourself »

Larger Example

In this example we see that it is possible to use only one method to count three different animals with three different increments for each animal. We achieve this by passing both the event object and the increment number:

Example

Both the increment size and the event object are passed as arguments with the method when a button is clicked. The reserved word '$event' is used to pass the event object with the method to tell what animal to count.

<div id="app">
  <div id="tigers">
    <img src="img_tiger.jpg">
    <button v-on:click="addAnimal($event,1)">+1</button>
    <button v-on:click="addAnimal($event,5)">+5</button>
    <button v-on:click="addAnimal($event,-1)">-1</button>
  </div>
  <div id="moose">
    <img src="img_moose.jpg">
    <button v-on:click="addAnimal($event,1)">+1</button>
    <button v-on:click="addAnimal($event,5)">+5</button>
    <button v-on:click="addAnimal($event,-1)">-1</button>
  </div>
  <div id="kangaroos">
    <img src="img_kangaroo.jpg">
    <button v-on:click="addAnimal($event,1)">+1</button>
    <button v-on:click="addAnimal($event,5)">+5</button>
    <button v-on:click="addAnimal($event,-1)">-1</button>
  </div>
  <ul>
    <li>Tigers: {{ tigers }} </li>
    <li>Moose: {{ moose }} </li>
    <li>Kangaroos: {{ kangaroos }} </li>
  </ul>
</div>

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
  const app = Vue.createApp({
    data() {
      return {
        tigers: 0,
        moose: 0,
        kangaroos: 0
      }
    },
    methods: {
      addAnimal(e,number) {
        if(e.target.parentElement.id==="tigers") {
          this.tigers+=number
        }
        else if(e.target.parentElement.id==="moose") {
          this.moose+=number
        }
        else {
          this.kangaroos+=number
        }
      }
    }
  })
 app.mount('#app')
</script>
Try it Yourself »

Vue Exercises

Test Yourself With Exercises

Exercise:

Write the missing code so that the 'writeText' method is called when the <div> tag is clicked.

<div id="app">
  <p>Click on the box below:</p>
  <div =>
    {{ text }}
  </div>
</div>

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
  const app = Vue.createApp({
    data() {
      return {
        text: ''
      }
    },
    : {
      writeText() {
        this. = 'Hello World!'
      }
    }
  })
  app.mount('#app')
</script>

Start the Exercise



×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.