vue learning: computed vs method
by giordanna
HTML
<script src="https://npmcdn.com/vue/dist/vue.js"></script>
<div id="app">
<button v-on:click="counter++">Increase</button>
<button v-on:click="secondCounter++">Increase second counter</button>
<button v-on:click="counter--">Decrease</button>
<p>Counter: {{ counter }} | {{ secondCounter }}</p>
<p>Result: {{ result() }} | {{ output }}</p>
</div>
JavaScript
new Vue({
el: '#app',
data: {
counter: 0,
secondCounter: 0
},
computed: {
output: function() {
console.log("called output");
return this.counter > 5 ? 'Greater than 5' : 'Smaller than 5';
}
},
watch: {
counter: function(value) {
var vm = this;
setTimeout( function () {
vm.counter = 0;
}, 2000);
}
},
methods: {
result: function() {
console.log("called result");
return this.counter > 5 ? 'Greater than 5' : 'Smaller than 5';
}
}
});