Understanding Vue's Computed Properties, Methods, and Watchers
Computed Properties vs Methods
computed properties and methods both process data from data, but with key differences. Computed properties cache results based on reactive dependencies, only recalculatign when dependencies change. Methods execute on every call during re-renders.
Use computed properties for expensive operations like large array processing where caching improves performance. Use methods for operations requiring fresh calculations each time, like function() { return Date.now() }.
Computed Propreties vs Watchers
Computed Properties:
- Cache results based on reactive dependencies
- Don't support asynchronous operations
- Derive values from other properties (many-to-one/one-to-one relationships)
- Default getter with optional setter
Watchers:
- Execute immediately when data changes (no caching)
- Suppport asynchronous operations
- Receive new and old values as parameters
- Trigger side effects when specific data changes (one-to-many relationships)
- Can use
deepoption for object property changes
Watcher Example
<div id="watch-example">
<p>
Ask a question:
<input v-model="question">
</p>
<p>{{ answer }}</p>
</div>
<script>
const watchExampleVM = new Vue({
el: '#watch-example',
data: {
question: '',
answer: 'Ask something!'
},
watch: {
question(newQ, oldQ) {
this.answer = 'Waiting...'
this.debouncedFetchAnswer()
}
},
created() {
this.debouncedFetchAnswer = _.debounce(this.fetchAnswer, 500)
},
methods: {
fetchAnswer() {
if (!this.question.includes('?')) {
this.answer = 'Questions need question marks!'
return
}
this.answer = 'Processing...'
axios.get('https://yesno.wtf/api')
.then(response => {
this.answer = _.capitalize(response.data.answer)
})
.catch(error => {
this.answer = `API Error: ${error}`
})
}
}
})
</script>