Vue Tutorial

Vue Methods

Functions that are listed in the’methods’ attribute of a Vue instance are called Vue methods.

Vue methods work well when used with event handling (v-on) to accomplish more sophisticated tasks.

Other than event handling, Vue methods have other uses.

The Vue 'methods' Property

In this tutorial, we have previously utilized the ‘data’ property, a Vue property that allows us to store values.

‘methods’ is another Vue attribute that allows us to store functions associated with the Vue instance. The Vue instance may store a method in the following manner:

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

Advice: To refer to a data property from within a method, we must write this. as a prefix.

We may write the code below to have the <div> element click the ‘writeText’ method:

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

This is how the example appears:

Example

The <div> element uses the v-on directive to listen for the ‘click’ event. The text is modified when the ‘writeText’ method is called in response to the ‘click’ event.

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

<script data-minify="1" src="https://codingfind.com/wp-content/cache/min/1/vue@3/dist/vue.global.js?ver=1742919599" defer></script>
<script>
  const app = Vue.createApp({
    data() {
      return {
        text: ''
      }
    },
    methods: {
      writeText() {
        this.text = 'Hello World!'
      }
    }
  })
  app.mount('#app')
</script>
				
			

Call a Method with the Event Object

By default, the event object is supplied together with the method when an event triggers the calling of a method. This is highly convenient as the event object holds a wealth of important information, such as the target object, the kind of event, and the mouse position at the time of the ‘click’ or ‘mousemove’ event.

Example

To listen for the ‘mousemove’ event, the <div> element uses the v-on directive. In order to obtain the mouse pointer location, the ‘mousePos’ method is triggered when the ‘mousemove’ event takes place. By default, the method sends the event object along with it.

To refer to “xPos” inside the Vue instance data property from the method, we must use the this. prefix.

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

<script data-minify="1" src="https://codingfind.com/wp-content/cache/min/1/vue@3/dist/vue.global.js?ver=1742919599" defer></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>
				
			

We can also make the background color change in response to the mouse pointer position in the x-direction if we extend the previous example by a single line. To modify the background-color in the style attribute, we only need to add v-bind:

Example

This example differs from the previous one in that v-bind is used to bind the background color to ‘xPos,’ setting the hsl ‘hue’ value to ‘xPos’.

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

To simulate writing in a notebook, the sample below uses an event object carrying text from the <textarea> element.

Example

The <textarea> tag uses the v-on directive to listen to the ‘input’ event, which happens any time the text inside the textarea element changes.

The ‘writeText’ function is called upon the occurrence of the ‘input’ event, and by default, the method is sent along with the event object, allowing us to retrieve the text from the <textarea> tag. The ‘writeText’ method modifies the ‘text’ property within the Vue instance. Vue automatically updates a span element that is configured to display the ‘text’ value using the double curly braces syntax.

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

<script data-minify="1" src="https://codingfind.com/wp-content/cache/min/1/vue@3/dist/vue.global.js?ver=1742919599" defer></script>
<script>
  const app = Vue.createApp({
    data() {
      return {
        text: ''
      }
    },
    methods: {
      writeText(event) {
        this.text = event.target.value
      }
    }
  })
  app.mount('#app')
</script>
				
			

Passing Arguments

Occasionally, we wish to pass a method argument when something happens.

Assume you are a forest warden who wishes to record the number of moose sightings. Occasionally, one or two moose may be spotted, but other times, a day may see over ten moose. A ‘-1’ button is included in case we have counted too many sightings, along with buttons to count sightings ‘+1’ and ‘+5’.

In this instance, we can call the method from each button with a distinct number, utilizing the same procedure for all three buttons. We can call a method with an argument in this way:

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

And this is the appearance of the ‘addMoose’ method:

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

Let’s look at an example that demonstrates how to pass an argument with a method.

Example

				
					<div id="app">
  <img decoding="async" src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E" alt="Vue Methods -" title="Vue Methods 1" data-lazy-src="img_moose.jpg"><noscript><img decoding="async" src="img_moose.jpg" alt="Vue Methods -" title="Vue Methods 1"></noscript>
  <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 data-minify="1" src="https://codingfind.com/wp-content/cache/min/1/vue@3/dist/vue.global.js?ver=1742919599" defer></script>
<script>
  const app = Vue.createApp({
    data() {
      return {
        count: 0
      }
    },
    methods: {
      addMoose(number) {
        this.count+=number
      }
    }
  })
 app.mount('#app')
</script>
				
			

Passing both an Argument and The Event Object

Wherever the method is called, we can utilize the reserved term “$event” to pass both the event object and an additional parameter, as in this case:

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

And this is the appearance of the method in the Vue instance:

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

Let’s now examine an example to understand how to use a method to pass both the event object and an additional argument.

Example

In this instance, a text and an event object are both passed to our method.

				
					<div id="app">
  <img decoding="async"
    src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E"
    id="tiger"
    v-on:click="myMethod($event,'Hello')" data-lazy-src="img_tiger.jpg"><noscript><img decoding="async"
    src="img_tiger.jpg"
    id="tiger"
    v-on:click="myMethod($event,'Hello')"></noscript>
  <p>"{{ msgAndId }}"</p>
</div>

<script data-minify="1" src="https://codingfind.com/wp-content/cache/min/1/vue@3/dist/vue.global.js?ver=1742919599" defer></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>
				
			

Larger Example

This example demonstrates how three different animals can be counted using three different increments for each animal using a single procedure. To do this, we pass the increment number in addition to the event object:

Example

When a button is clicked, the method receives two arguments: the increment size and the event object. The event object is passed the method to determine which animal to count using the reserved phrase “$event.”

				
					<div id="app">
  <div id="tigers">
    <img decoding="async" src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E" alt="Vue Methods -" title="Vue Methods 2" data-lazy-src="img_tiger.jpg"><noscript><img decoding="async" src="img_tiger.jpg" alt="Vue Methods -" title="Vue Methods 2"></noscript>
    <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 decoding="async" src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E" alt="Vue Methods -" title="Vue Methods 1" data-lazy-src="img_moose.jpg"><noscript><img decoding="async" src="img_moose.jpg" alt="Vue Methods -" title="Vue Methods 1"></noscript>
    <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 decoding="async" src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E" alt="Vue Methods -" title="Vue Methods 4" data-lazy-src="img_kangaroo.jpg"><noscript><img decoding="async" src="img_kangaroo.jpg" alt="Vue Methods -" title="Vue Methods 4"></noscript>
    <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 data-minify="1" src="https://codingfind.com/wp-content/cache/min/1/vue@3/dist/vue.global.js?ver=1742919599" defer></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>
				
			
Share this Doc

Vue Methods

Or copy link

Explore Topic