Lzh on GitHub

监听值为真值的简写。

用法

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))
// 这个
whenever(ready, () => console.log(state))

// 等同于:
watch(ready, (isReady) => {
  if (isReady)
    console.log(state)
})

回调函数

watch 相同,回调函数将通过 cb(value, oldValue, onInvalidate) 调用。

whenever(height, (current, lastHeight) => {
  if (current > lastHeight)
    console.log(`Increasing height by ${current - lastHeight}`)
})

计算属性

watch 相同,你可以传递一个 getter 函数来在每次更改时进行计算。

// 这个
whenever(
  () => counter.value === 7,
  () => console.log('counter is 7 now!'),
)

选项

选项和默认值与 watch 相同。

// 这个
whenever(
  () => counter.value === 7,
  () => console.log('counter is 7 now!'),
  { flush: 'sync' },
)

类型声明

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 declare function whenever<T>(
  source: WatchSource<T | false | null | undefined>,
  cb: WatchCallback<T>,
  options?: WheneverOptions,
): WatchHandle