如何手动阻止观察者?

发布于 2025-01-30 09:01:24 字数 614 浏览 0 评论 0原文

我需要停止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技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

执手闯天涯 2025-02-06 09:01:24

“手表”功能返回一个函数,该功能在调用时会停止观察器:

const unwatch = watch(someProperty, () => { });

unwatch(); // It will stop watching

仅观看一次更改:

const unwatch = watch(someProperty, () => {
   // Do what your have to do

   unwatch();
});

The "watch" function returns a function which stops the watcher when it is called :

const unwatch = watch(someProperty, () => { });

unwatch(); // It will stop watching

To watch a change only once:

const unwatch = watch(someProperty, () => {
   // Do what your have to do

   unwatch();
});
过期情话 2025-02-06 09:01:24

从VUE 3.5开始,除了终止外,还提供了暂停,如以下文档示例所示:

const { stop, pause, resume } = watch(() => {})

// temporarily pause the watcher
pause()

// resume later
resume()

// stop
stop()

Starting from Vue 3.5, in addition to termination, pausing is also available, as illustrated in the following documentation example:

const { stop, pause, resume } = watch(() => {})

// temporarily pause the watcher
pause()

// resume later
resume()

// stop
stop()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文