1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | const app = new Vue({ el: '#app', created(){ this.updateNow(); // We want update to happen at first state too. }, data: { changingProperty:[] }, methods:{ updateNow(){ // Code needs to be updated } }, watch:{ changingProperty(){ this.updateNow(); } } }); |
Above code is the normal code to watch the changes in property.
This portion can simply be changed too:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | const app = new Vue({ el: '#app', data: { changingProperty:[] }, methods:{ updateNow(){ // Code needs to be updated } }, watch:{ changingProperty:{ handler: 'updateNow', immediate: true, // We want this to be called on created too. } } }); |
No more messing inside both created methods and watcher. Watcher alone is enough.
In general, the methods like updateNow methods are case specific, so to refactor again,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | const app = new Vue({ el: '#app', data: { changingProperty:[] }, watch:{ changingProperty:{ handler: updateNow(){ // Code needs to be updated }, immediate: true, // We want this to be called on created too. } } }); |
The property that needs to be watched are just handled by watchers alone now.
Everything is awesome.
Be First to Comment