Vue.js - Reacting to Changes with Computed Properties
by hyeyoon
HTML
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
<!-- <button v-on:click="increase">Increase</button>
<button v-on:click="decrease">Decrease</button> -->
<button v-on:click="counter++">Increase</button>
<button v-on:click="counter--">Decrease</button>
<button v-on:click="secondCounter++">Increase Second</button>
<p>Counter: {{ counter }} | {{ secondCounter }}</p>
<p>Result: {{ result() }} | {{ output }}</p>
</div>
JavaScript
new Vue({
el: '#app',
data: {
counter: 0,
secondCounter: 0
//result: ''
},
computed: {
// computed의 경우 필요한 경우에 계산이 됨
output: function() {
console.log('Computed')
return this.counter > 5 ? 'Greater 5' : 'Smaller 5';
}
},
watch: {
counter: function(value) {
var vm = this;
setTimeout(function() {
vm.counter = 0;
}, 2000);
}
},
methods: {
// secondCounted에서는 호출될 필요가 없지만, method의 경우 계속 호출한다는 단점이 있음 따라서 computed를 사용하는 것을 권장
result: function() {
console.log('Method');
return this.counter > 5 ? 'Greater 5' : 'Smaller 5';
}
//increase: function() {
//this.counter++;
//this.result = this.counter > 5 ? 'Greater 5' : 'Smaller 5'
//},
//decrease: function() {
//this.counter--;
//this.result = this.counter > 5 ? 'Greater 5' : 'Smaller 5'
//}
}
})