Skip to content

watchTriggerable

Category
Export Size
942 B
Last Changed
last month

可手动触发的 Watch

Demo

数值:0

日志(500 毫秒延迟)

用法

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

typescript
import { watchTriggerable } from '@vueuse/core'
import { nextTick, ref } from 'vue'

const source = ref(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 将解决此问题。

typescript
import { watchTriggerable } from '@vueuse/core'
import { ref } from 'vue'

const source = ref(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"

类型声明

显示类型声明
typescript
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>

Source

SourceDemoDocs

贡献者

Anthony Fu
丶远方
Anthony Fu
Ayaka Rizumu

变更日志

No recent changes

Released under the MIT License.