Computed Properties Caching
Let’s understand another important aspect of computed properties i.e. Caching.
Computed Properties in Vue Instance are dependent on the variables that are reactive, Vue also caches the computed properties and it changes only when the dependencies change.
Let’s understand this by the below example.
Consider an application which has two input boxes, one of them is bound to the Vue data property via v-model and another is not.
<div id="app">
<input type="text" v-model="name" />
<input type="text" id="surname" value="Snow" />
<button @click="saveSurname"> Save Surname </button><br/><br/>
<output>{{computedFullName}}</output>
</div>
And here is our Vue instance
Use coupon 5balloons on this Cloudways Affiliate URL to get special discount.
let surname = 'Snow';
var app = new Vue({
el: '#app',
data: {
name: 'John',
},
computed: {
computedFullName: function () {
return this.name + ' ' + surname;
}
},
methods: {
saveSurname: function(){
surname = this.$el.querySelector('#surname').value;
}
}
});
- We have defined a variable named
surname
outside the Vue Instance. - We have defined a computed property named
computedFullName
, that joins the name data property with surname to make it a full Name. - We also a method defined
saveSurname
that gets invoked on clicking the Save Surname button.
Running this application will display two input fields, one for the name and one for the surname, and one button specifically to save the surname.
Running the app, the value of computedFullName is John Snow.
If you change the value of name
field, the computed property will change as it’s dependency it changing and will show realtime updates.
If you change the value of the surname field and then click on Save Surname. Nothing will happen because the surname field is not reactive and the value of the computed property is now cached.
Now, change the value of name
field again. And you’ll see that the computedProperty
now takes into account the new value of Surname as well.
We just experimented with computed properties to verify that they are cached and are saved in memory until we change the value on which they are dependent on.