如何手动阻止观察者?
我需要停止watch()
,但是文档并没有真正解释如何做到这一点。
该观察者运行直到循环完成(1000秒):
const state = reactive({
val: 0
})
watch(() => state.val, () => {
console.log(state.val)
})
for (let i = 1; i < 1000; i++) {
setTimeout(function timer() {
state.val = state.val + 1
}, i * 1000);
}
我如何在跑步后停止观察者?使用WatchEffect
不是一个选项,因为对于我的用例,观察者需要在停止之前运行几次,这在这个简化的示例中没有描述。根据我的理解,观察效应
仅运行一次(启动后)。
I need to stop watch()
but the docs don't really explain how to do that.
This watcher runs until the loop is finished (1000 seconds):
const state = reactive({
val: 0
})
watch(() => state.val, () => {
console.log(state.val)
})
for (let i = 1; i < 1000; i++) {
setTimeout(function timer() {
state.val = state.val + 1
}, i * 1000);
}
How do I stop the watcher after running once? Using watchEffect
is not an option because for my use case the watcher needs to run several times before stopped, which is not described in this simplified example. From my understanding watchEffect
runs only once (after initiation).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
“手表”功能返回一个函数,该功能在调用时会停止观察器:
仅观看一次更改:
The "watch" function returns a function which stops the watcher when it is called :
To watch a change only once:
从VUE 3.5开始,除了终止外,还提供了暂停,如以下文档示例所示:
watch()
Starting from Vue 3.5, in addition to termination, pausing is also available, as illustrated in the following documentation example:
watch()