Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Apply VueUse composables in Vue 3/Nuxt projects to replace custom implementations with battle-tested utilities.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/watchTriggerable.md
1---2category: Watch3---45# watchTriggerable67Watch that can be triggered manually89## Usage1011A `watch` wrapper that supports manual triggering of `WatchCallback`, which returns an additional `trigger` to execute a `WatchCallback` immediately.1213```ts14import { watchTriggerable } from '@vueuse/core'15import { nextTick, shallowRef } from 'vue'1617const source = shallowRef(0)1819const { trigger, ignoreUpdates } = watchTriggerable(20source,21v => console.log(`Changed to ${v}!`),22)2324source.value = 'bar'25await nextTick() // logs: Changed to bar!2627// Execution of WatchCallback via `trigger` does not require waiting28trigger() // logs: Changed to bar!29```3031### `onCleanup`3233When you want to manually call a `watch` that uses the onCleanup parameter; simply taking the `WatchCallback` out and calling it doesn't make it easy to implement the `onCleanup` parameter.3435Using `watchTriggerable` will solve this problem.3637```ts38import { watchTriggerable } from '@vueuse/core'39import { shallowRef } from 'vue'4041const source = shallowRef(0)4243const { trigger } = watchTriggerable(44source,45async (v, _, onCleanup) => {46let canceled = false47onCleanup(() => canceled = true)4849await new Promise(resolve => setTimeout(resolve, 500))50if (canceled)51return5253console.log(`The value is "${v}"\n`)54},55)5657source.value = 1 // no log58await trigger() // logs (after 500 ms): The value is "1"59```6061## Type Declarations6263```ts64export interface WatchTriggerableReturn<65FnReturnT = void,66> extends WatchIgnorableReturn {67/** Execute `WatchCallback` immediately */68trigger: () => FnReturnT69}70type OnCleanup = (cleanupFn: () => void) => void71export type WatchTriggerableCallback<V = any, OV = any, R = void> = (72value: V,73oldValue: OV,74onCleanup: OnCleanup,75) => R76export declare function watchTriggerable<77T extends Readonly<MultiWatchSources>,78FnReturnT,79>(80sources: [...T],81cb: WatchTriggerableCallback<82MapSources<T>,83MapOldSources<T, true>,84FnReturnT85>,86options?: WatchWithFilterOptions<boolean>,87): WatchTriggerableReturn<FnReturnT>88export declare function watchTriggerable<T, FnReturnT>(89source: WatchSource<T>,90cb: WatchTriggerableCallback<T, T | undefined, FnReturnT>,91options?: WatchWithFilterOptions<boolean>,92): WatchTriggerableReturn<FnReturnT>93export declare function watchTriggerable<T extends object, FnReturnT>(94source: T,95cb: WatchTriggerableCallback<T, T | undefined, FnReturnT>,96options?: WatchWithFilterOptions<boolean>,97): WatchTriggerableReturn<FnReturnT>98```99