useThrottledRefHistory
useRefHistory 的简写形式,带节流 (throttled) 过滤器。
Demo
<script setup lang="ts">
import { formatDate, useCounter, useThrottledRefHistory } from '@vueuse/core'
import { shallowRef } from 'vue'
function format(ts: number) {
return formatDate(new Date(ts), 'YYYY-MM-DD HH:mm:ss')
}
const delay = shallowRef(1000)
const { count, inc, dec } = useCounter()
const { history, undo, redo, canUndo, canRedo } = useThrottledRefHistory(
count,
{
deep: true,
throttle: delay,
capacity: 10,
trailing: true,
},
)
</script>
<template>
<div>Count: {{ count }}</div>
<button @click="inc()">
Increment
</button>
<button @click="dec()">
Decrement
</button>
<span class="ml-2">/</span>
<button :disabled="!canUndo" @click="undo()">
Undo
</button>
<button :disabled="!canRedo" @click="redo()">
Redo
</button>
<br>
<span>Delay (in ms):</span>
<input v-model="delay" type="number">
<br>
<br>
<note>History (limited to 10 records for demo)</note>
<div class="code-block mt-4">
<div v-for="i in history" :key="i.timestamp">
<span class="opacity-50 mr-2 font-mono">{{ format(i.timestamp) }}</span>
<span class="font-mono">{ value: {{ i.snapshot }} }</span>
</div>
</div>
</template>
使用
这个函数会在计数器值 刚改变后立即 拍摄第一个快照,并在 延迟 1000 毫秒后 拍摄第二个快照。
import { useThrottledRefHistory } from '@vueuse/core'
import { shallowRef } from 'vue'
const counter = shallowRef(0)
const { history, undo, redo } = useThrottledRefHistory(counter, { deep: true, throttle: 1000 })
类型声明
export type UseThrottledRefHistoryOptions<Raw, Serialized = Raw> = Omit<
UseRefHistoryOptions<Raw, Serialized>,
"eventFilter"
> & {
throttle?: MaybeRef<number>
trailing?: boolean
}
export type UseThrottledRefHistoryReturn<
Raw,
Serialized = Raw,
> = UseRefHistoryReturn<Raw, Serialized>
/**
* Shorthand for [useRefHistory](https://vueuse.org/useRefHistory) with throttled filter.
*
* @see https://vueuse.org/useThrottledRefHistory
* @param source
* @param options
*/
export declare function useThrottledRefHistory<Raw, Serialized = Raw>(
source: Ref<Raw>,
options?: UseThrottledRefHistoryOptions<Raw, Serialized>,
): UseThrottledRefHistoryReturn<Raw, Serialized>