whenever
用於監看真值的簡寫。
用法
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.dev.org.tw/whenever
*/
export declare function whenever<T>(
source: WatchSource<T | false | null | undefined>,
cb: WatchCallback<T>,
options?: WheneverOptions,
): WatchHandle