Skip to content

watchTriggerable

类别
导出体积
570 B
上次更改
9 months ago

可手动触发的 Watch

示例

数值:0

日志(500 毫秒延迟)

用法

watch 的一个包装器,支持手动触发 WatchCallback,返回一个额外的 trigger 来立即执行 WatchCallback

ts
import { 
watchTriggerable
} from '@vueuse/core'
import {
nextTick
,
shallowRef
} from 'vue'
const
source
=
shallowRef
(0)
const {
trigger
,
ignoreUpdates
} =
watchTriggerable
(
source
,
v
=>
console
.
log
(`Changed to ${
v
}!`),
)
source
.
value
= 'bar'
await
nextTick
() // logs: Changed to bar!
// 通过 `trigger` 执行 WatchCallback 不需要等待
trigger
() // logs: Changed to bar!

onCleanup

当你想手动调用使用 onCleanup 参数的 watch 时;简单地将 WatchCallback 拿出来调用并不容易实现 onCleanup 参数。

使用 watchTriggerable 将解决此问题。

ts
import { 
watchTriggerable
} from '@vueuse/core'
import {
shallowRef
} from 'vue'
const
source
=
shallowRef
(0)
const {
trigger
} =
watchTriggerable
(
source
,
async (
v
,
_
,
onCleanup
) => {
let
canceled
= false
onCleanup
(() =>
canceled
= true)
await new
Promise
(
resolve
=>
setTimeout
(
resolve
, 500))
if (
canceled
)
return
console
.
log
(`The value is "${
v
}"\n`)
}, )
source
.
value
= 1 // no log
await
trigger
() // logs (after 500 ms): The value is "1"

类型声明

显示类型声明
ts
export interface 
WatchTriggerableReturn
<
FnReturnT
= void>
extends WatchIgnorableReturn { /** Execute `WatchCallback` immediately */
trigger
: () =>
FnReturnT
} type
OnCleanup
= (
cleanupFn
: () => void) => void
export type
WatchTriggerableCallback
<
V
= any,
OV
= any,
R
= void> = (
value
:
V
,
oldValue
:
OV
,
onCleanup
:
OnCleanup
,
) =>
R
export declare function
watchTriggerable
<
T
extends
Readonly
<
WatchSource
<unknown>[]>,
FnReturnT
,
>(
sources
: [...
T
],
cb
:
WatchTriggerableCallback
<
MapSources
<
T
>,
MapOldSources
<
T
, true>,
FnReturnT
>,
options
?:
WatchWithFilterOptions
<boolean>,
):
WatchTriggerableReturn
<
FnReturnT
>
export declare function
watchTriggerable
<
T
,
FnReturnT
>(
source
:
WatchSource
<
T
>,
cb
:
WatchTriggerableCallback
<
T
,
T
| undefined,
FnReturnT
>,
options
?:
WatchWithFilterOptions
<boolean>,
):
WatchTriggerableReturn
<
FnReturnT
>
export declare function
watchTriggerable
<
T
extends object,
FnReturnT
>(
source
:
T
,
cb
:
WatchTriggerableCallback
<
T
,
T
| undefined,
FnReturnT
>,
options
?:
WatchWithFilterOptions
<boolean>,
):
WatchTriggerableReturn
<
FnReturnT
>

源码

源码演示文档

贡献者

Anthony Fu
一纸忘忧
Anthony Fu
IlyaL
James Garbutt
Ayaka Rizumu

更新日志

59f75 - feat(toValue): deprecate toValue from @vueuse/shared in favor of Vue's native
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)