設定
這些顯示了 VueUse 中大多數函式的通用設定。
事件過濾器
從 v4.0 開始,我們提供了事件過濾器系統,可以靈活地控制何時觸發事件。 例如,您可以使用 throttleFilter
和 debounceFilter
來控制事件觸發速率
ts
import { debounceFilter, throttleFilter, useLocalStorage, useMouse } from '@vueuse/core'
// changes will write to localStorage with a throttled 1s
const storage = useLocalStorage('my-key', { foo: 'bar' }, { eventFilter: throttleFilter(1000) })
// mouse position will be updated after mouse idle for 100ms
const { x, y } = useMouse({ eventFilter: debounceFilter(100) })
此外,您可以使用 pausableFilter
暫時暫停某些事件。
ts
import { pausableFilter, useDeviceMotion } from '@vueuse/core'
const motionControl = pausableFilter()
const motion = useDeviceMotion({ eventFilter: motionControl.eventFilter })
motionControl.pause()
// motion updates paused
motionControl.resume()
// motion updates resumed
響應式時間控制
VueUse 的函式遵循 Vue 的響應式系統預設值,用於刷新時機(flush timing)。
對於類似 watch
的組合式函式(例如 pausableWatch
、whenever
、useStorage
useRefHistory
),預設值為 { flush: 'pre' }
。 這表示它們將緩衝失效的 effect 並非同步地刷新它們。 這避免了在同一個「tick」中發生多個狀態變更時不必要的重複調用。
與 watch
相同,VueUse 允許您通過傳遞 flush
選項來配置時間控制
ts
import { pausableWatch } from '@vueuse/core'
import { ref } from 'vue'
const counter = ref(0)
const { pause, resume } = pausableWatch(
counter,
() => {
// Safely access updated DOM
},
{ flush: 'post' },
)
flush 選項 (預設: 'pre'
)
'pre'
: 在同一個 'tick' 中緩衝失效的 effect,並在渲染之前刷新它們'post'
: 與 'pre' 類似,但會在元件更新後觸發,因此您可以訪問更新後的 DOM'sync'
: 強制 effect 始終同步觸發
注意: 對於類似 computed
的組合式函式 (例如 syncRef
controlledComputed
),當 flush 時間控制可配置時,預設值更改為 { flush: 'sync' }
,使其與 Vue 中 computed refs 的工作方式一致。
可配置的全局依賴項
從 v4.0 開始,訪問瀏覽器 API 的函式將提供一個選項欄位,供您指定全局依賴項(例如 window
、document
和 navigator
)。 預設情況下,它將使用全局實例,因此在大多數情況下,您無需擔心。 當使用 iframes 和測試環境時,此設定非常有用。
ts
import { useMouse } from '@vueuse/core'
// accessing parent context
const parentMousePos = useMouse({ window: window.parent })
const iframe = document.querySelector('#my-iframe')
// accessing child context
const childMousePos = useMouse({ window: iframe.contentWindow })
ts
// testing
const mockWindow = { /* ... */ }
const { x, y } = useMouse({ window: mockWindow })