設定
これらは、VueUse のほとんどの関数の一般的な設定を示しています。
イベントフィルター
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
リアクティブタイミング
VueUse の関数は、可能な限り、flush タイミングについて Vue のリアクティビティシステムのデフォルトに従います。
watch
に似たコンポーザブル (例: pausableWatch
、whenever
、useStorage
useRefHistory
) のデフォルトは { flush: 'pre' }
です。これは、無効化されたエフェクトをバッファリングし、非同期的にフラッシュすることを意味します。これにより、同じ「ティック」内で複数の状態変更が発生した場合に、不要な重複呼び出しが回避されます。
watch
と同様に、VueUse では flush
オプションを渡すことでタイミングを設定できます。
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'
: 同じ「ティック」で無効化されたエフェクトをバッファリングし、レンダリングの前にフラッシュします'post'
: 'pre' のように非同期ですが、コンポーネントの更新後に発生するため、更新された DOM にアクセスできます'sync'
: エフェクトを常に同期的にトリガーします
注: computed
に似たコンポーザブル (例: syncRef
controlledComputed
) の場合、flush タイミングが設定可能な場合、デフォルトは { flush: 'sync' }
に変更され、Vue での computed ref の動作に合わせられます。
設定可能なグローバル依存関係
v4.0 から、ブラウザ API にアクセスする関数は、グローバル依存関係 (例: window
、document
、および navigator
) を指定するためのオプションフィールドを提供します。デフォルトではグローバルインスタンスを使用するため、ほとんどの場合、気にする必要はありません。この設定は、iframe やテスト環境で作業する場合に役立ちます。
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 })
// testing
const mockWindow = { /* ... */ }
const { x, y } = useMouse({ window: mockWindow })