LoginSignup
1
1

More than 3 years have passed since last update.

【vue】methodsの省略表記と注意点(アロー関数は使えない)

Posted at

【vue】methodsの省略表記と注意点

・OK:functionを使わない省略表記を使うのが一般的。
・NG:アロー関数を使う

省略表記
methods:{
    メソッド名(){
      処理
    }
 }

メソッド名の後ろにカッコを直接つける。


NG事例(アロー関数)

アロー関数を使った場合、処理の中でプロパティを呼び出すことができない。

NG事例(アロー関数)
export default {
  data(){
    return{
      text: "ボタン"
    }
  },
  methods:{
    メソッド名:()=>{
      console.log(this.text)
    }
 }
}
エラー内容
[Vue warn]: Error in v-on handler: "TypeError: Cannot read property 'text' of undefined"

textを正しく設定してるのに、呼び出すことができない。


参考(3つの処理)

  1. 省略形
  2. function使用(冗長表記)
  3. アロー関数(NG事例)
Methods.vue
<template>
  <div>
    <v-btn @click="showConsole1">
      {{text}}1
    </v-btn>

    <br>

    <v-btn @click="showConsole2">
      {{text}}2
    </v-btn>

    <br>

    <v-btn @click="showConsole3">
      {{text}}3
    </v-btn>
  </div>
</template>

<script>
export default {
  data(){
    return{
      text: "ボタン"
    }
  },
  methods:{
    showConsole1(){
      console.log("showConsole1:", this.text)
    },
    showConsole2:function(){
      console.log("showConsole2:", this.text)
    },
    showConsole3:()=>{
      console.log("showConsole3:", this.text)
    }
  }
}
</script>

▼ブラウザの表記

image.png

▼実行結果

image.png

ボタン1、2は正常に作動するが、アロー関数を用いた3はエラーとなる。

1
1
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
1
1