主题
whenever
观察值是否真实的简写。
¥Shorthand for watching value to be truthy.
用法
¥Usage
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)
})
回调函数
¥Callback Function
与 watch
相同,回调将通过 cb(value, oldValue, onInvalidate)
调用。
¥Same as watch
, the callback will be called with cb(value, oldValue, onInvalidate)
.
ts
whenever(height, (current, lastHeight) => {
if (current > lastHeight)
console.log(`Increasing height by ${current - lastHeight}`)
})
计算的
¥Computed
与 watch
相同,你可以传递一个 getter 函数来计算每次更改。
¥Same as watch
, you can pass a getter function to calculate on each change.
ts
// this
whenever(
() => counter.value === 7,
() => console.log('counter is 7 now!'),
)
选项
¥Options
选项和默认值与 watch
相同。
¥Options and defaults are same with 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/whenever
*/
export declare function whenever<T>(
source: WatchSource<T | false | null | undefined>,
cb: WatchCallback<T>,
options?: WheneverOptions,
): WatchHandle