Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(whenever): override once option (#3800)
- Loading branch information
Showing
2 changed files
with
69 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,18 +1,36 @@ | ||
import type { WatchCallback, WatchOptions, WatchSource } from 'vue-demi' | ||
import { watch } from 'vue-demi' | ||
import { nextTick, watch } from 'vue-demi' | ||
|
||
export interface WheneverOptions extends WatchOptions { | ||
/** | ||
* Only trigger once when the condition is met | ||
* | ||
* Override the `once` option in `WatchOptions` | ||
* | ||
* @default false | ||
*/ | ||
once?: boolean | ||
} | ||
|
||
/** | ||
* Shorthand for watching value to be truthy | ||
* | ||
* @see https://vueuse.org/whenever | ||
*/ | ||
export function whenever<T>(source: WatchSource<T | false | null | undefined>, cb: WatchCallback<T>, options?: WatchOptions) { | ||
return watch( | ||
export function whenever<T>(source: WatchSource<T | false | null | undefined>, cb: WatchCallback<T>, options?: WheneverOptions) { | ||
const stop = watch( | ||
source, | ||
(v, ov, onInvalidate) => { | ||
if (v) | ||
if (v) { | ||
if (options?.once) | ||
nextTick(() => stop()) | ||
cb(v, ov, onInvalidate) | ||
} | ||
}, | ||
options, | ||
{ | ||
...options, | ||
once: false, | ||
} as WatchOptions, | ||
) | ||
return stop | ||
} |