LoginSignup
2
0

More than 5 years have passed since last update.

初心者がVue.jsの公式ガイドを勉強するメモ イベントハンドリング編

Last updated at Posted at 2018-01-30

イベントハンドリング編

今回のお題です

https://jp.vuejs.org/v2/guide/events.html

  • ブラウザー結果は、掲載しませんので、実際に確認してみてください。

メソッドイベントハンドラ

イベントの購読

  • App.vue
<template lang="pug">
  #App
    div: button(@click="counter += 1") Add 1
    div: button(@click="greet") Greet
    p {{ counter }} times.
</template>

<script>

export default {
  name: 'app',
  data  () {
    return {
      counter: 0,
      name: 'ヤス'
    }
  },
  methods: {
    greet (event) {
      alert('Hello' + this.name + '!')
      if (event) {
        alert(event.target.tagName)
      }
    }
  }
}

</script>
  • ここは、復習セクションですね。

インラインメソッドハンドラ

  • App.vue
<template lang="pug">
  #App
    div {{ greet.hello }}
    div: button(@click="say('hi!')") Say hi
    div: button(@click="say('what?')") Say what
    div: button(@click="saySet('saySet!')") Say Set method
</template>

<script>

export default {
  name: 'app',
  data  () {
    return {
      greet: {
         hello: ''
      }
    }
  },
  computed: {
  },
  methods: {
    say (event) {
      return this.greet.hello = event
    },
    saySet (event) {
      return this.$set(this.greet, 'hello', event)
    }

  }
}

</script>
  • 前章(リストレンダリング編)で覚えた, setメソッドも使って見ます。
  • 引数での受け渡し OK ですね。  

イベント修飾子

  • App.vue
<template lang="pug">
  #App
    div: a(@click.prevent="href='https://google.com'" :href="href") google ?
    div: a(@click="href='https://google.com'" :href="href") google ?
    // クリックしてしまったら、ブラウザの左矢印で戻ってください。
</template>

<script>

export default {
  name: 'app',
  data  () {
    return {
      href: 'https://www.yahoo.co.jp/'
    }
  },
  computed: {
  },
  methods: {
  }
}

</script>
  • このあたりのバブリング/キャプチャリングの話はよくわかっていないのですが、例がわかりやすいpreventのサンプルを作って見ました。
  • preventは画面推移の抑止に使われます。 この場合は、aタグの基本動作が抑止されます。
  • 修飾子は、数珠つなぎにできるみたいなので、動作がイメージ出来ていると組み合わせもできそうですね。 

キー修飾子

  • App.vue
<template lang="pug">
  #App
    p {{ inputText}}
    //- enter key を離すと実行
    input(@keyup.13="inputMethod(inputText)" v-model="inputText")
</template>

<script>
import Vue from 'vue'

export default {
  name: 'app',
  data () {
    return {
      inputText: ''
    }
  },
  methods: {
    inputMethod(input) {
      alert(input)
    }
  },
  computed: {
  }
}

</script>

  • キー入力のコントロールが出来るみたいです。 ちなみにサンプルは、エンターキーが押下状態から戻った時に、中の式が実行されます。

自動キー修飾子

  • キー割り当ての拡張みたいですね。今は用途が思いつかないです。
  • マウスコントロール、システムコントロールも説明でわかるかと思います。
  • イベントの発生を細かく制御する仕組みみたいです。

  • 今回はこれで終了です。 あっさりになってしまいました。
2
0
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
2
0