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
と同様に、各変更時に計算を行うゲッター関数を渡すことができます。
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' },
)
型定義
typescript
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.dokyumento.jp/whenever
*/
export declare function whenever<T>(
source: WatchSource<T | false | null | undefined>,
cb: WatchCallback<T>,
options?: WheneverOptions,
): WatchHandle