跳到主要内容

whenever

分类
导出大小
173 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 相同,你可以传入一个 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' },
)

类型声明

ts
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

来源

源码文档

贡献者

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

更新日志

0a9ed - feat!: 放弃对 Vue 2 的支持,优化打包并清理 (#4349)
v10.9.0
bd946 - feat: 覆盖 once 选项 (#3800)

根据 MIT 许可证发布。