跳到主要内容

配置

这里展示了 VueUse 大多数函数的通用配置。

事件过滤器

从 v4.0 开始,我们提供了事件过滤器系统,以灵活控制事件触发的时机。例如,您可以使用 throttleFilterdebounceFilter 来控制事件触发频率。

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 响应式系统的默认刷新时机

对于类 watch 的可组合函数(例如 watchPausablewheneveruseStorageuseRefHistory),默认是 { flush: 'pre' }。这意味着它们将缓冲失效的副作用并异步刷新它们。这避免了在同一“tick”中发生多个状态突变时不必要的重复调用。

watch 相同,VueUse 允许您通过传递 flush 选项来配置时机。

ts
import { 
watchPausable
} from '@vueuse/core'
import {
ref
} from 'vue'
const
counter
=
ref
(0)
const {
pause
,
resume
} =
watchPausable
(
counter
,
() => { // Safely access updated DOM }, {
flush
: 'post' },
)

flush 选项(默认:'pre'

  • 'pre':在同一“tick”中缓冲失效的副作用并在渲染前刷新它们。
  • 'post':与 'pre' 类似,但异步执行并在组件更新后触发,以便您可以访问更新后的 DOM。
  • 'sync':强制副作用始终同步触发。

注意: 对于类 computed 的可组合函数(例如 syncRefcomputedWithControl),当刷新时机可配置时,默认会更改为 { flush: 'sync' },以使其与 Vue 中计算属性的工作方式保持一致。

可配置的全局依赖项

从 v4.0 开始,访问浏览器 API 的函数将提供一个选项字段,供您指定全局依赖项(例如 windowdocumentnavigator)。默认情况下,它将使用全局实例,因此在大多数情况下,您无需担心。此配置在处理 iframe 和测试环境时非常有用。

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 })

根据 MIT 许可证发布。