<div id="app">
<button v-on:click="count++"> Increment</button>
<button v-on:click="count--"> Decrement</button>
<p> Count: {{ count }}</p>
<button v-on:click="count2++"> Increment Count 2</button>
<p> Count2: {{ count2 }}</p>
<p class="color-red"> Odd / even for count : {{ output }} - {{ result() }} </p>
</div>
<script type="text/javascript">
new Vue({
el: "#app",
data:{
count : 0,
count2 : 0
},
computed:{
output: function(){
console.log('computed');
return this.count % 2 == 0 ? 'Even' : 'Odd' ;
}
},
methods:{
result: function(){
console.log('methods');
return this.count % 2 == 0 ? 'Even' : 'Odd' ;
}
}
});
</script>
Demo http://vue.toihid.com/section-2/reacting_with_computed_properties.php
According to the above code, if we do inspect in a browser then we can see
- click Increment button : executes computed and method
- click Decrement button : executes computed and method
- click Increment count 2 button : executes only method not the computed properties. Because the output computed.property is related to count property not the count2
- Note: result methods executes every time whereas, computed properties only executes for related changes of own property.
- So computed property is more efficient for performance and space.