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'
}
}
})
hey, I'm sharing some code here.
Just a heads up, when the value of the counter changes, the watch property is triggered and after 2 seconds, the counter is reset to 0.
This script is flawless! but there's one thing that confuses me about the watch property. why does the counter method in the watch property only work when using the closure feature?
counter(value) {
var vm = this;
setTimeout(() => {
vm.counter = 0;
}, 2000)
}
this does the trick!
counter(value) {
setTimeout(() => {
this.counter = 0;
}, 2000)
}
but this doesn't do the job! (counter remains unchanged even after 2 sec)
what could be causing this situation?