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 Server Vue Certificate

Vue v-on Directive

Like event handling in plain JavaScript, the v-on directive in Vue tells the browser:

  1. which event to listen to ('click', 'keydown', 'mouseover', etc)
  2. what to do when that event occurs

Examples using v-on

Let's take a look at some examples to see how v-on can be used with different events and different code to run when these events occur.

Note: To run more advanced code when an event occurs we need to introduce Vue methods. Learn about Vue methods on the next page in this tutorial.


onclick Event

The v-on directive allows us to perform actions based on specified events.

Use v-on:click to perform action when the element is clicked.

Example

The v-on directive is used on the <button> tag to listen to the 'click' event. When the 'click' event occurs the 'lightOn' data property is toggled between 'true' and 'false', making the yellow <div> behind the lightbulb visible/hidden.

<div id="app">
  <div id="lightDiv">
    <div v-show="lightOn"></div>
    <img src="img_lightBulb.svg">
  </div>
  <button v-on:click="lightOn = !lightOn">Switch light</button>
</div>

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
  const app = Vue.createApp({
    data() {
      return {
        lightOn: false
      }
    }
  })
  app.mount('#app')
</script>
Try it Yourself »

oninput Event

Use v-on:input to perform action when the element gets an input, like a keystroke inside a text field.

Example

Count the number of keystroke for a input text field:

<div id="app">
  <input v-on:input="inpCount++">
  <p>{{ 'Input events occured: ' + inpCount }}</p>
</div>

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

mousemove Event

Use v-on:mousemove to perform action when the mouse pointer moves over an element.

Example

Change the background color of a <div> element whenever the mouse pointer moves over it:

<div id="app">
  <p>Move the mouse pointer over the box below</p>
  <div v-on:mousemove="colorVal=Math.floor(Math.random()*360)"
       v-bind:style="{backgroundColor:'hsl('+colorVal+',80%,80%)'}">
  </div>
</div>

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
  const app = Vue.createApp({
    data() {
      return {
        colorVal: 50
      }
    }
  })
  app.mount('#app')
</script>
Try it Yourself »

Use v-on in a v-for Loop

You can also use the v-on directive inside a v-for loop.

The items of the array are available for each iteration inside the v-on value.

Example

Display a list based on the food array and add an click event for each item that will use a value from the array item to change the source of an image.

<div id="app">
  <img v-bind:src="imgUrl">
  <ol>
    <li v-for="food in manyFoods" v-on:click="imgUrl=food.url">
      {{ food.name }}
    </li>
  </ol>
</div>

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
  const app = Vue.createApp({
    data() {
      return {
        imgUrl: 'img_salad.svg',
        manyFoods: [
          {name: 'Burrito', url: 'img_burrito.svg'},
          {name: 'Salad', url: 'img_salad.svg'},
          {name: 'Cake', url: 'img_cake.svg'},
          {name: 'Soup', url: 'img_soup.svg'}
        ]
      }
    }
  })
  app.mount('#app')
</script>
Try it Yourself »

Shorthand for v-on

The shorthand for 'v-on' is simply '@'.

Example

Here we just write '@' instead of 'v-on':

<button @:click="lightOn = !lightOn">Switch light</button>
Try it Yourself »

We will start using @ syntax a little later in this tutorial.


Vue Exercises

Test Yourself With Exercises

Exercise:

Complete the code so that the image toggles when the button is clicked.

<template>
  <button ="showImg = !showImg">
    Toggle image
  </button>
  <img src="flower.jpg" alt="flower" v-show="showImg">
</template>

<script>
  export default {
    data() {
      return {
        : true
      }
    }
  }
</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.