Skip to content

whenever

类别
导出体积
97 B
上次更改
4 months ago

监视值为真的简写形式。

用法

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

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

回调函数

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

typescript
whenever(height, (current, lastHeight) => {
  if (current > lastHeight)
    console.log(`高度增加了 ${current - lastHeight}`)
})

计算属性

watch 相同,你可以传递一个获取器函数来在每次更改时计算。

typescript
// 这个
whenever(
  () => counter.value === 7,
  () => console.log('counter 现在为 7!'),
)

选项

选项和默认值与 watch 相同。

typescript
// 这个
whenever(
  () => counter.value === 7,
  () => console.log('counter 现在为 7!'),
  { flush: 'sync' },
)

类型声明

typescript
export interface WheneverOptions extends WatchOptions {
  /**
   * 当条件满足时仅触发一次
   *
   * 覆盖 `WatchOptions` 中的 `once` 选项
   *
   * @default false
   */
  once?: boolean
}
/**
 * 监视值为真的简写形式
 *
 * @see https://vueuse.org/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

更新日志

v10.9.0 on 2/27/2024
bd946 - feat: override once option (#3800)