[英]reason for working properly only when using closure in this method in vue.js watch object
index.html 的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 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. 更改计数器值后,手表属性就会知道这一点,并在2秒后将计数器更改为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? 为什么watch属性中的counter方法仅在使用闭包功能时才起作用?
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) (即使2秒后计数器也不会变为零)
why does it happen? 为什么会发生?
it's resolved. 解决了 my mistake. 我的错。 thank you Daniel! 谢谢丹尼尔! actually i'm new here, i don't know exactly whether it's right to end up with this question like this... 其实我是新来的,我不知道以这样的问题结束是否正确……
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.