いつもお世話になっております。
監視プロパティwatcherの挙動を勉強していて気づいたことを備忘録。
監視プロパティwatch内ではアロー関数を使うべきではない
nuxt.jsで、監視プロパティであるwatchのオプションdeepの挙動を調べていたら、怒られました。
<script>
export default {
data() {
return {
colors: [
{ name: 'red' },
{ name: 'blue' },
{ name: 'green' },
],
}
},
watch: {
colors: {
handler:(newValue, oldValue) => {
console.log('updated!')
},
deep: true,
},
},
}
</script>



はい
なぜなら、アロー関数はthisの挙動が変わってしまうため。アロー関数は親のコンテキストをバインドしており、thisの挙動が意図しているVueインスタンスとは異なってしまう。
This rules disallows using arrow functions to defined watcher.The reason is arrow functions bind the parent context, so
this
will not be the Vue instance as you expect.(see here for more details (opens new window))
thisの挙動についてはここがわかりやすかったです!



【JavaScript】アロー関数式を学ぶついでにthisも復習する話 - Qiita
対象読者 ES6を詳しくは知らない なんとなくJavaScriptを書けるけど、JSのthisの特性についてまだよく知らない アロー関数式を知らない、または知っているけど実装経験がない 概要 JavaScriptのES6で導入...
というわけで、こう
<script> export default { data() { return { colors: [ { name: 'red' }, { name: 'blue' }, { name: 'green' }, ], } }, watch: { colors: { // handler:(newValue, oldValue) => { handler(newValue, oldValue) { console.log('updated!') }, deep: true, }, }, } </script>