Vue Tutorial

Vue Event Modifiers

Vue’s event modifiers allow us to handle events in a more direct and effective manner by changing the way events cause methods to run.

When combined with the Vue v-on directive, event modifiers can be used, for instance, to:

  • Stop HTML forms from submitting by default (v-on:submit.prevent)
  • Verify that an event (v-on:click.once) can only be called once the page has loaded.
  • Choose the keyboard key (v-on:keyup.enter) that will be used as an event to execute a method.

How To Modify The v-on Directive

Event modifiers are used to specify in further detail how an event should be handled.

To use event modifiers, first attach a tag to an event as previously observed:

				
					<button v-on:click="createAlert">Create alert</button>
				
			

We can now add the.once modifier to more precisely describe that the button click event should only fire once the page loads. This looks like this:

				
					<button v-on:click.once="createAlert">Create alert</button>
				
			

Here’s an illustration using the .once modifier:

Example

The <button> tag’s .once modifier is used to restrict the method’s execution to the initial occurrence of the ‘click’ event.

				
					<div id="app">
  <p>Click the button to create an alert:</p>
  <button v-on:click.once="creteAlert">Create Alert</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({
    methods: {
      createAlert() {
        alert("Alert created from button click")
      }
    }
  })
  app.mount('#app')
</script>
				
			

Note: Using event modifiers makes handling events more easier, however handling events inside the method is also feasible.

Different v-on Modifiers

Event modifiers are applied in various contexts. Event modifiers can be used in conjunction with one another as well as when listening to keyboard and mouse click events.

It is possible to utilize the event modifier .once both in response to keyboard and mouse click events.

Keyboard Key Event Modifiers

Keydown, Keypress, and Keyup are the three distinct keyboard event kinds.

We are able to designate precisely which key to listen to in the aftermath of a key event for each type of key event. To just a few, we have .space, .enter, .w, and .up.

To determine the value of a particular key on your own, you can write the key event to the web page or to the console using console.log(event.key):

Example

The value ‘key’ from the event object is published to the console and the webpage when the keydown keyboard event initiates the ‘getKey’ method.

				
					<input v-on:keydown="getKey">
<p> {{ keyValue }} </p>
				
			
				
					data() {
  return {
    keyValue = ''
  }
},
methods: {
  getKey(evt) {
    this.keyValue = evt.key
    console.log(evt.key)
  }
}
				
			

Additionally, we have the option to restrict the event to only occur in response to a mouse click or key press made in conjunction with system modifier keys .alt, .shift, .ctrl, or .meta. On Windows systems, the Windows key is represented by the system modifier key .meta; on Apple computers, it is the command key.

Key ModifierDetails
.[Vue key alias]The most common keys have their own aliases in Vue:
  • .enter
  • .tab
  • .delete
  • .esc
  • .space
  • .up
  • .down
  • .left
  • .right
.[letter]Specify the letter that comes when you press the key. As an example: use the .s key modifier to listen to the ‘S’ key.
.[system modifier key].alt, .ctrl, .shift or .meta. These keys can be used in combination with other keys, or in combination with mouse clicks.

Example

When a user puts a’s’ inside the <textarea> tag, utilize the .s modifier to produce an alert.

				
					<div id="app">
  <p>Try pressing the 's' key:</p>
  <textarea v-on:keyup.s="createAlert"></textarea>
</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({
    methods: {
      createAlert() {
        alert("You pressed the 'S' key!")
      }
    }
  })
  app.mount('#app')
</script>
				
			

Combine Keyboard Event Modifiers

Additionally, event modifiers can be combined with one another to require multiple simultaneous events in order for the method to be called.

Example

When “s” and “ctrl” are pressed simultaneously inside the <textarea> tag, use the .s and .ctrl modifiers together to generate an alert.

				
					<div id="app">
  <p>Try pressing the 's' key:</p>
  <textarea v-on:keydown.ctrl.s="createAlert"></textarea>
</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({
    methods: {
      createAlert() {
        alert("You pressed the 'S' and 'Ctrl' keys, in combination!")
      }
    }
  })
  app.mount('#app')
</script>
				
			

Mouse Button Modifiers

Although we can use the .left, .center, or .right modifiers to indicate which mouse button was hit, we can still use v-on:click to respond to a mouse click.

Trackpad users: To make a right click, you might need to use two fingers or the lower right corner of your computer’s trackpad.

Example

Whenever a user right-clicks within the <div> element, the background color is changed:

				
					<div id="app">
  <div v-on:click.right="changeColor"
       v-bind:style="{backgroundColor:'hsl('+bgColor+',80%,80%)'}">
    <p>Press right mouse button here.</p>
  </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 {
        bgColor: 0
      }
    },
    methods: {
      changeColor() {
        this.bgColor+=50
      }
    }
  })
  app.mount('#app')
</script>
				
			

Additionally, a system modifier key can be used in conjunction with mouse clicking events.

Example

When a user right-clicks within the <div> element while holding down the ‘ctrl’ key, the background color is altered:

				
					<div id="app">
  <div v-on:click.right.ctrl="changeColor"
       v-bind:style="{backgroundColor:'hsl('+bgColor+',80%,80%)'}">
    <p>Press right mouse button here.</p>
  </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 {
        bgColor: 0
      }
    },
    methods: {
      changeColor() {
        this.bgColor+=50
      }
    }
  })
  app.mount('#app')
</script>

				
			

The modifier of .prevent. In addition to the .right modification, prohibit can be used to stop the default drop-down menu from showing up when we right-click.

Example

When you right-click on the <div> element to alter its background color, the drop-down menu is not displayed:

				
					<div id="app">
  <div v-on:click.right.prevent="changeColor"
       v-bind:style="{backgroundColor:'hsl('+bgColor+',80%,80%)'}">
    <p>Press right mouse button here.</p>
  </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 {
        bgColor: 0
      }
    },
    methods: {
      changeColor() {
        this.bgColor+=50
      }
    }
  })
  app.mount('#app')
</script>
				
			

Using event.preventDefault() inside the method would make it possible to stop the drop-down menu from displaying after a right-click, but the Vue .prevent modifier makes the code easier to read and manage.

Additionally, you can respond to mouse clicks on the left button in conjunction with additional modifiers, such as click.left.shift:

Example

To alter the picture, hold down the ‘shift’ keyboard key and click the left mouse button on the <img> tag.

				
					<div id="app">
  <p>Hold 'Shift' key and press left mouse button:</p>
  <img v-on:click.left.shift="changeImg" v-bind:src="imgUrl">
</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 {
        imgUrlIndex: 0,
        imgUrl: 'img_tiger_square.jpeg',
        imgages: [
          'img_tiger_square.jpeg',
          'img_moose_square.jpeg',
          'img_kangaroo_square.jpeg'
        ]
      }
    },
    methods: {
      changeImg() {
        this.imgUrlIndex++
        if(this.imgUrlIndex>=3){
          this.imgUrlIndex=0
        }
        this.imgUrl = this.images[this.imgUrlIndex]
      }
    }
  })
  app.mount('#app')
</script>
				
			
Share this Doc

Vue Event Modifiers

Or copy link

Explore Topic