Movatterモバイル変換


[0]ホーム

URL:


Menu
×
See More 
Sign In
+1 Get Certified Upgrade Teachers Spaces Get Certified Upgrade Teachers Spaces
   ❮   
     ❯   

Vue Tutorial

Vue HOMEVue IntroVue DirectivesVue v-bindVue v-ifVue v-showVue v-forVue EventsVue v-onVue MethodsVue Event ModifiersVue FormsVue v-modelVue CSS BindingVue Computed PropertiesVue WatchersVue Templates

Scaling Up

Vue Why, How and SetupVue First SFC PageVue ComponentsVue PropsVue v-for ComponentsVue $emit()Vue Fallthrough AttributesVue Scoped StylingVue Local ComponentsVue SlotsVue v-slotVue Scoped SlotsVue Dynamic ComponentsVue TeleportVue HTTP RequestVue Template RefsVue Lifecycle HooksVue Provide/InjectVue RoutingVue Form InputsVue AnimationsVue Animations with v-forVue BuildVue Composition API

Vue Reference

Vue Built-in AttributesVue Built-in ComponentsVue Built-in ElementsVue Component InstanceVue DirectivesVue Instance OptionsVue Lifecycle Hooks

Vue Examples

Vue ExamplesVue ExercisesVue QuizVue SyllabusVue Study PlanVue ServerVue Certificate

Vuev-on Directive

Like event handling in plain JavaScript, thev-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 usingv-on

Let's take a look at some examples to see howv-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.

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

Example

Thev-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

Usev-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

Usev-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 thev-on directive inside av-for loop.

The items of the array are available for each iteration inside thev-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 forv-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 ourterms of use,cookies andprivacy policy.

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


[8]ページ先頭

©2009-2025 Movatter.jp