跳到主要內容

watchIgnorable

類別
導出大小
433 B
上次變更
3 週前
別名
ignorableWatch

可忽略的 watch

示範

值:0

日誌

用法

擴展的 watch,返回額外的 ignoreUpdates(updater)ignorePrevAsyncUpdates() 以忽略對來源的特定更新。

ts
import { watchIgnorable } from '@vueuse/core'
import { nextTick, shallowRef } from 'vue'

const source = shallowRef('foo')

const { stop, ignoreUpdates } = watchIgnorable(
  source,
  v => console.log(`Changed to ${v}!`),
)

source.value = 'bar'
await nextTick() // logs: Changed to bar!

ignoreUpdates(() => {
  source.value = 'foobar'
})
await nextTick() // (nothing happened)

source.value = 'hello'
await nextTick() // logs: Changed to hello!

ignoreUpdates(() => {
  source.value = 'ignored'
})
source.value = 'logged'

await nextTick() // logs: Changed to logged!

Flush 時序

watchIgnorable 接受與 watch 相同的選項,並使用相同的預設值。因此,預設情況下,composable 使用 flush: 'pre' 運作。

ignorePrevAsyncUpdates

此功能僅適用於異步 flush 'pre''post'。如果使用 flush: 'sync',則 ignorePrevAsyncUpdates() 是無操作,因為 watch 會在每次來源更新後立即觸發。它仍然為同步 flush 提供,以便程式碼可以更通用。

ts
import { watchIgnorable } from '@vueuse/core'
import { nextTick, shallowRef } from 'vue'

const source = shallowRef('foo')

const { ignorePrevAsyncUpdates } = watchIgnorable(
  source,
  v => console.log(`Changed to ${v}!`),
)

source.value = 'bar'
await nextTick() // logs: Changed to bar!

source.value = 'good'
source.value = 'by'
ignorePrevAsyncUpdates()

await nextTick() // (nothing happened)

source.value = 'prev'
ignorePrevAsyncUpdates()
source.value = 'after'

await nextTick() // logs: Changed to after!

類型宣告

顯示類型宣告
typescript
export type IgnoredUpdater = (updater: () => void) => void
export interface WatchIgnorableReturn {
  ignoreUpdates: IgnoredUpdater
  ignorePrevAsyncUpdates: () => void
  stop: WatchStopHandle
}
export declare function watchIgnorable<
  T extends Readonly<WatchSource<unknown>[]>,
  Immediate extends Readonly<boolean> = false,
>(
  sources: [...T],
  cb: WatchCallback<MapSources<T>, MapOldSources<T, Immediate>>,
  options?: WatchWithFilterOptions<Immediate>,
): WatchIgnorableReturn
export declare function watchIgnorable<
  T,
  Immediate extends Readonly<boolean> = false,
>(
  source: WatchSource<T>,
  cb: WatchCallback<T, Immediate extends true ? T | undefined : T>,
  options?: WatchWithFilterOptions<Immediate>,
): WatchIgnorableReturn
export declare function watchIgnorable<
  T extends object,
  Immediate extends Readonly<boolean> = false,
>(
  source: T,
  cb: WatchCallback<T, Immediate extends true ? T | undefined : T>,
  options?: WatchWithFilterOptions<Immediate>,
): WatchIgnorableReturn
export { watchIgnorable as ignorableWatch }

原始碼

原始碼示範文件

貢獻者

Anthony Fu
Anthony Fu
IlyaL
Yue JIN
sun0day
lvjiaxuan
webfansplz

更新日誌

v12.0.0-beta.1 於 2024/11/21
0a9ed - feat!: 移除 Vue 2 支援,最佳化 bundles 並清理 (#4349)

根據 MIT 許可證發布。