30
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Vue.jsでアロー関数を使うと詰む

Last updated at Posted at 2018-05-15

概要

この1週間、Vue.jsを使っていて、詰んだことを書きます。

何があったの?

Vue.jsでは、関数内で"this"を使うことができます。this を用いて、Vue内の他のdataの値や関数を取得できる……はずだった。

new Vue({
	el: "#root",
	data: {colorcode: "#FF00FF"},
	methods: {
		change_code: (event) => {
			console.log(this.colorcode);
		});
	}
});

ですが、change_code 関数内から呼び出した、this.colorcodeの値は "undefined" のままです。いろいろ試してみたけれど、やはり "undefined" のままでした。
原因は、アロー関数「(event) => {...}」を使ったせいでした。なので、アロー関数を、アロー関数でない形「function(event) {...}」に書き換えれば、値を取得することができるようになります。

new Vue({
	el: "#root",
	data: {colorcode: "#FF00FF"},
	methods: {
		change_code: function(event) {
			console.log(this.colorcode);
		});
	}
});

おわりに

対処法が分かれば簡単ですが、なかなか気づけなかったので、Qiitaに投稿しておきます。皆さまも、お気をつけくださいませ。

30
17
5

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
30
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?