LoginSignup
3

More than 5 years have passed since last update.

Vue Component内methodsのアロー関数式内でdataを扱う

Posted at

やりたいこと

とある.vueファイル(エラー)
export default {
  data: () => {
    return {
      test: 0
    }
  },
  methods: {
    testfunc: () => {
      this.test++ // エラー
    }
    /*
    testfunc2: function () {
      this.test++ // こちらはうまくいく
    }
     */
  },
  created () {
    this.testfunc() // ここではthisが使えている
  }
}

うまくいかない原因

  • アロー演算子() => {}内のthisはこのvmを参照していないため

対処法

とある.vueファイル
var vm // --①
export default {
  data: () => {
    return {
      test: 0
    }
  },
  methods: {
    testfunc: () => {
      vm.test++ // 👏
    }
  },
  created () {
    vm = this // --②
    this.testfunc()
  }
}

ポイント

①vm用の変数を確保
②vm内にcreatedmountedを使ってvmを代入

もやもや

  • 出来ればvarを使わずに書きたい
  • 外に仮置きしないで実装する方法は無いんだろうか…

もっときれいに書く方法が有れば、教えていただけるとありがたいです。

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
3