index.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>VueJS</title>
<script src="vue.js"></script>
</head>
<body>
<div id="app">
<button @click="counter++">increase</button>
<button @click="counter--">decrease</button>
<p>Counter: {{counter}}</p>
<p>Result: {{ result() }} | {{ output }}</p>
</div>
</body>
</html>
<script src="app.js"></script>
app.js
new Vue({
el: "#app",
data: {
counter: 0
},
computed: {
output() {
console.log('Computed!')
return this.counter > 5 ? 'Greater than 5' : 'Smaller than 5'
}
},
watch: {
counter(value) {
var vm = this;
setTimeout(() => {
vm.counter = 0;
}, 2000)
}
},
methods: {
result() {
console.log('Method!')
return this.counter > 5 ? 'Greater than 5' : 'Smaller than 5'
}
}
})
hi, here is my code.
once counter value is changed, watch property knows this and after 2 sec, change counter into 0.
this code has no problem! but i got one thing that don't understand on watch property. why does counter method in watch property work only when using closure feature?
counter(value) {
var vm = this;
setTimeout(() => {
vm.counter = 0;
}, 2000)
}
this do work!
counter(value) {
setTimeout(() => {
this.counter = 0;
}, 2000)
}
but this doesn't work! (counter doesn't become zero even after 2 sec)
why does it happen?