refThrottled

refThrottled

ref の値の変更をスロットルします。

使用法

import { refThrottled } from '@vueuse/core'
import { shallowRef } from 'vue'

const input = shallowRef('')
const throttled = refThrottled(input, 1000)

オブジェクト ref の例。

import { refThrottled } from '@vueuse/core'
import { shallowRef } from 'vue'

const data = shallowRef({
  count: 0,
  name: 'foo',
})
const throttled = refThrottled(data, 1000)

data.value = { count: 1, name: 'foo' }
console.log(throttled.value) // { count: 1, name: 'foo' } (即時)

data.value = { count: 2, name: 'bar' }
data.value = { count: 3, name: 'baz' }
data.value = { count: 4, name: 'qux' }
console.log(throttled.value) // { count: 1, name: 'foo' } (まだ最初の値)

// 1000ms 後、次の変更が適用されます
await sleep(1100)
data.value = { count: 5, name: 'final' }
await nextTick()
console.log(throttled.value) // { count: 5, name: 'final' } (更新済み)

Trailing

トレーリングの変更を監視したくない場合は、3番目のパラメータを false に設定します(デフォルトは true です):

import { refThrottled } from '@vueuse/core'
import { shallowRef } from 'vue'

const input = shallowRef('')
const throttled = refThrottled(input, 1000, false)

Leading

コールバックを即時に呼び出すことを許可します(ms タイムアウトの先頭で)。この動作を望まない場合は、4番目のパラメータを false に設定します(デフォルトは true です):

import { refThrottled } from '@vueuse/core'
import { shallowRef } from 'vue'

const input = shallowRef('')
const throttled = refThrottled(input, 1000, undefined, false)

推奨読書