LoginSignup
17
12

More than 1 year has passed since last update.

Vueのcomputedで詰まった話(this)

Posted at

結論

算出プロパティを定義するためにアロー関数を使用しない方がいい。

背景

私はVueの案件のスタートが
最初からvue-property-decoratorを用いた
クラススタイルのコンポーネントであった。

@Component
export default class HelloWorld extends Vue {
  firstName = 'John'
  lastName = 'Doe'

  get name() {
    return this.firstName + ' ' + this.lastName
  }

  set name(value) {
    const splitted = value.split(' ')
    this.firstName = splitted[0]
    this.lastName = splitted[1] || ''
  }
}

なので逆に、生JavaScriptで
このような書き方をするのには慣れていなかった。

computed: {
  fullName: {
    get: function () {
      return this.firstName + ' ' + this.lastName
    },
    set: function (newValue) {
      const names = newValue.split(' ')
      this.firstName = names[0]
      this.lastName = names[names.length - 1]
    }
  }
}

現象

そこで起きたのが、このような問題だった。

computed: {
  fullName: {
    get: () => {
      return this.firstName + ' ' + this.lastName
    },
    set: (newValue) => {
      const names = newValue.split(' ')
      this.firstName = names[0]
      this.lastName = names[names.length - 1]
    }
  }
}

すると、コンソールで

firstNameはundefindです

みたいな怒られ方をした。

firstNameはVuexのGetterから取得していたが、
他のmethod内やコンポーネント内で使用する際には
このようなエラーは起こっていなかった。

原因

Vueでは、
コンストラクタを呼び出してインスタンスを生成した時、
インスタンス中の this はインスタンスそのものを指す。

しかし、アロー関数内のthisは、そのような動きをしない。

なぜならば、アロー関数は呼び出された場所をthisとするからである。

そのため、現象の例では、
computed 内でアロー関数を宣言した結果、
thisを指し示す箇所が本来参照したいものと異なり、
「そのプロパティは存在しない」、というエラーが出た
ということだった。

参考

17
12
1

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