LoginSignup
1
1

More than 3 years have passed since last update.

【Vue.js】v-onディレクティブの書き方・使い方

Last updated at Posted at 2020-12-09

はじめに

UIを実装する上でボタンをクリックすると文字の色や大きさが変化したり、要素の表示が切り替わったりなどさまざまな場合があると思います。
Vueでは、v-onディレクティブに発火させたいタイミングのイベントと関数を書くだけでこのような処理を簡単に実装できます。
本記事では学習したv-onディレクティブの書き方と実装例を備忘のためにアウトプットしたいと思います。

v-onの書き方

<div v-on:イベント名="処理(関数)"></div>

省略して書くこともできます。

<div @イベント名="処理(関数)"></div>
<div id="app">
    <button v-on:click="count++">count++</button>
    <p>Count: {{ count }}</p>
</div>

<script>
const app = new Vue({
   el:'#app',
   data:{
      count:0,
   },
   methods:{
    plus:function(){
     this.count++
    }
   }
});
</script>

指定可能なイベントハンドラ

v-onディレクティブで指定可能なイベントは実行されているブラウザがサポートしているものすべてとなります。
イベントについてはMDN web docs:イベントリファレンス、ブラウザのサポート状況はCan I useで確認することができます。

image.png

インラインメソッド

特別な $event変数を使うことでメソッドにDOMイベントを渡すことができます。

<div id="app">
  <p>{{ message }}</p>
  <button @click="say('hello', $event)">hello</button>
</div>

<script>
const app = new Vue({
  el: '#app',
  data: {
    message: 'greeting'
  },
  methods: {
    say:function(message, event){
      console.log(event)
      this.message = message
    }
  }
})
</script>

参照

Vue.js Directives: v-on
Vue.js EventHandling: Listening to Events

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