LoginSignup
10
9

More than 3 years have passed since last update.

Vue.jsのイベント修飾子について理解する

Posted at

概要

本記事では、Vue.jsで用意されているイベント修飾子について.stop.preventを例にしていまとめていきます。

.stop

処理内容はJavaScriptにおけるDOMのEventオブジェクトのevent.stopPropagation()と同じ。
下記の例では、mousemoveによりpタグの上にマウスを乗せるとイベントが発火するようになっています。
そのpタグの中にspanタグを入れていますが、このspanタグの上にマウスを乗せた時だけはイベントを発火させたくないという時に.stopを使用します。
イベント発火をさせたくないspanタグにv-on:mousemove.stopを書いてあげることで、"ここでは反応させたくない"の文字の上ではイベントが発火しないようになります。

index.html
<div id="app">
  <p id="sampleText" v-on:mousemove="mousePosition">ここにマウスを載せると下のX、Yの値が変わるよ
    <span v-on:mousemove.stop>ここでは反応させたくない</span>
  </p>
  <p id="result">X:{{x}}, Y:{{y}}</p>
</div>
index.js
new Vue({
  el: '#app',
  data: {
    x: 0,
    y: 0
  },
  methods: {
    mousePosition: function(event) {
      this.x = event.clientX;
      this.y = event.clientY;
    }
  }
})

.prevent

処理内容はJavaScriptにおけるDOMのEventオブジェクトのevent.preventDefault()と同じ。
下記の例では、aタグのリンク先としてGoogleを設定しています。
本来であればクリックした時にGoogleのサイトに遷移しますが、v-on:click.preventと記述するとaタグとしてのデフォルトの挙動を妨げることができます。

index.html
<div id="app">
  <a v-on:click.prevent href="https://google.com">リンク</a>
</div>
index.js
new Vue({
  el: '#app'
})

最後に

Vue.jsで用意されているイベント修飾子をうまく利用する事で、シンプルなコードを書く事ができるようになります。
他にも利用可能なイベント修飾子はたくさんあるので調べてみてください!

10
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
9