Using Vue.js Computed Properties to Reflect Changes in the VDOM
Explain how to define computed properties in a Vue.js component and how it facilitates minimizing updates to the Virtual DOM.
<div id='app'>
<p>Original price: {{ originalPrice }}</p>
<p>Discounted price: {{ discountedPrice }}</p>
</div>
HTML structure featuring an instance of the Vue component that displays both the original and the discounted prices.
new Vue({
el: '#app',
data: {
originalPrice: 100,
discountRate: 0.2
},
computed: {
// A computed property that calculates the discounted price
discountedPrice: function() {
return this.originalPrice - (this.originalPrice * this.discountRate);
}
}
});
Vue instance defining a computed property 'discountedPrice' that automatically recalculates whenever its dependent properties, 'originalPrice' or 'discountRate', change.
<style>
p {
font-family: 'Arial', sans-serif;
}
</style>
CSS styling for the paragraph elements to use the Arial font-family.