【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つの処理)
- 省略形
- function使用(冗長表記)
- アロー関数(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>
▼ブラウザの表記
![]() |
---|
▼実行結果
![]() |
---|
ボタン1、2は正常に作動するが、アロー関数を用いた3はエラーとなる。