跳到主要內容

whenever

類別
匯出大小
173 B
上次變更
4 個月前

用於監看真值的簡寫。

用法

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' },
)

類型宣告

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.dev.org.tw/whenever
 */
export declare function whenever<T>(
  source: WatchSource<T | false | null | undefined>,
  cb: WatchCallback<T>,
  options?: WheneverOptions,
): WatchHandle

原始碼

原始碼文件

貢獻者

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

更新日誌

v12.0.0-beta.1 於 2024/11/21
0a9ed - feat!: 移除 Vue 2 支援,優化 bundle 並清理 (#4349)
v10.9.0 於 2024/2/27
bd946 - feat: 覆寫 once 選項 (#3800)

以 MIT 授權條款發布。