本章主要展示对大部分VueUse
函数通用的配置
Event Filters
从v4.0
开始,我们提供了事件过滤系统来灵活控制何时触发事件。比如你可以使用throttleFilter
和debounceFilter
来控制事件触发率。
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
暂时暂停某些事件。
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
Reactive Timing
VueUse
的函数尽可能遵守响应式系统下默认的时间刷新机制。
对于类watch
的组件,比如pausableWatch
,whenever
,useStorage
、useRefHistory
的默认值都是{flush:'pre'}
。它们将缓冲无效的结果并异步刷新这些结果。这避免了在同一tick
中发生多个状态变化时不必要的重复调用。
与watch
的配置方式相同,VueUse
允许您通过配置flush
选项来控制刷新时机。
const { pause, resume } = pausableWatch(
() => {
// Safely access updated DOM
},
{ flush: 'post' },
)
flush 的选项(默认值为**pre**
)
pre
: 在同一tick
缓冲无效结果,并在渲染前刷新他们。post
: 在同一tick
缓冲无效结果,并在渲染后刷新,使你能访问更新的DOMsync
: 强制使效果同步触发。
Note: 对于类computed
的组件,比如syncRef
、controlledComputed
,当flush
可以配置时,默认值为sync
,使他们与Vue中的computed refs
效果一致。
Configurable Global Dependencies
从v4.0
开始,访问浏览器API的函数将为您提供一个选项字段,用于指定全局依赖项(例如window
、document
和navigator
)。默认情况下,它将使用全局实例,因此在大多数情况下,您不必担心它。此配置在iframes和测试环境的情况下非常有用。
// accessing parent context
const parentMousePos = useMouse({ window: window.parent })
const iframe = document.querySelect('#my-iframe')
// accessing child context
const childMousePos = useMouse({ window: iframe.contentWindow })
// testing
const mockWindow = { /* ... */ }
const { x, y } = useMouse({ window: mockWindow })