whenever
当值为真值时,进行监听的简写。
用法
js
import { useAsyncState, whenever } from '@vueuse/core'
const { state, isReady } = useAsyncState(
fetch('https://jsonplaceholder.typicode.com/todos/1').then(t => t.json()),
{},
)
whenever(isReady, () => console.log(state))ts
// this
whenever(ready, () => console.log(state))
// is equivalent to:
watch(ready, (isReady) => {
if (isReady)
console.log(state)
})回调函数
与 watch 相同,回调函数将被调用,参数为 cb(value, oldValue, onInvalidate)。
ts
whenever(height, (current, lastHeight) => {
if (current > lastHeight)
console.log(`Increasing height by ${current - lastHeight}`)
})计算属性
与 watch 相同,你可以传入一个 getter 函数来在每次更改时进行计算。
ts
// this
whenever(
() => counter.value === 7,
() => console.log('counter is 7 now!'),
)选项
选项和默认值与 watch 相同。
ts
// this
whenever(
() => counter.value === 7,
() => console.log('counter is 7 now!'),
{ flush: 'sync' },
)类型声明
ts
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.cn/whenever
*/
export declare function whenever<T>(
source: WatchSource<T | false | null | undefined>,
cb: WatchCallback<T>,
options?: WheneverOptions,
): WatchHandle