目的
苗字と名を変えるたびに、名前もそれにつれて変えていく。然も、タイムログは1000ms 設定せよ。
元コード
`
watch: {
firstName (newVal ) {
setTimeout (function () {
this.fullName = newVal + '-' + this.lastName
},1000)
},
lastName (newVal ){
setTimeout (function (){
this.fullName = this.firstName + '-' + newVal
},1000)
}
}
`
ミス
自動的にページは更新することができなくなり、ミスが起こった。動画をまねてコードを改めてする。
改善
watch:{
firstName(newVal){
setTimeout(() => {
this.fullName = newVal + '-' + this.lastName
},1000)
},
lastName(newVal){
setTimeout(() => {
this.fullName = this.firstName + '-' + newVal
},1000)
}
理由について
this
元コードの中、「this」はwindowという対象を指しているのに対し、改善後、矢印関数の中の「this」はVUEの実例対象、即ちVMを指している。
まとめ
無論、元コードの「this」を「VM」を入れ替えれば、異常なし。
しかし、矢印関数は「this」を指す対象を変えることができ、利用する前、改めて慎重に考えれば無難だろうと思う。