設定
這裡展示了 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 時序 預設值。
對於類似 watch
的 composables (例如 pausableWatch
、whenever
、useStorage
、useRefHistory
),預設值為 { flush: 'pre' }
。這表示它們將緩衝失效的 effects 並異步刷新它們。這避免了在同一個 "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' 中緩衝失效的 effects,並在渲染前刷新它們'post'
:類似 'pre' 的異步行為,但在元件更新後觸發,以便您可以訪問更新後的 DOM'sync'
:強制 effect 始終同步觸發
注意: 對於類似 computed
的 composables (例如 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 })