跳到内容

每当

类别
导出大小
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.org.cn/whenever
 */
export declare function whenever<T>(
  source: WatchSource<T | false | null | undefined>,
  cb: WatchCallback<T>,
  options?: WheneverOptions,
): WatchHandle

来源

SourceDocs

贡献者

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

更新日志

v12.0.0-beta.1 于 11/21/2024
0a9ed - feat!: 删除 Vue 2 支持,优化捆绑包并清理 (#4349)
v10.9.0 于 2/27/2024
bd946 - feat: 覆盖 once 选项 (#3800)

根据 MIT 许可证发布。