LoginSignup
53
33

More than 5 years have passed since last update.

【Vue】v-onで複数の関数を呼び出す方法

Last updated at Posted at 2018-07-28

イベントハンドラ

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

その名の通り v-on は呼び出したいメソッドの名前を指定する

<div @click="method"></div>
  • インラインメソッドハンドラ

メソッド名を直接指定する代わりに、インライン JavaScript 式でメソッドを指定する

<div @click="method('Hello')"></div>
var vm = new Vue({
  // ・・・
  methods: {
    method: function (message) {
      alert(message)
    }
  }
})

単一のv-onイベントで複数の関数を呼び出す方法

単一の関数を分割して呼び出し

<div @click="firstMethod(); secondMethod()"></div>
var vm = new Vue({
  // ・・・
  methods: {
    firstMethod: function () {
      // ・・・
    }
    secondMethod: function () {
      // ・・・
    }
  }
})

複数の関数を実行するラッパー関数を実行

<div @click="multipleHandler()"></div>
var vm = new Vue({
  // ・・・
  methods: {
    multipleHandler: function () {
      this.firstMethod()
      this.secondMethod()
    }
    firstMethod: function () {
      // ・・・
    }
    secondMethod: function () {
      // ・・・
    }
  }
})

まとめ

多くのイベントハンドラのロジックはより複雑になっていくので、v-on 属性の値に JavaScript 式を記述し続けるのは現実的ではありません。

ドキュメントにあるように、複数の処理を行う必要がある場合は、
両方を含むラッパー(複合関数)を実行する方が良いかもしれません😷

メソッドイベントハンドラのロジックとして単一の関数呼び出しのみを行う方が、Vue的にはベストプラクティスなのでしょうか?😪

参考

53
33
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
53
33