コンテンツへスキップ

whenever

カテゴリ
エクスポートサイズ
97 B
最終更新日
先週

真偽値になる値を監視するための簡略表記です。

使用方法

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

ソースコード

ソースコードドキュメント

コントリビューター

Anthony Fu
Anthony Fu
Chizuki
freakzlike
donotloveshampo
Chung, Lian
Alex Kozack

変更ログ

v12.0.0-beta.1 2024/11/21
0a9ed - feat!: Vue 2サポートの削除、バンドルの最適化、クリーンアップ (#4349)
v10.9.0 2024/2/27
bd946 - feat: onceオプションの上書き (#3800)

MITライセンスの下でリリースされています。