useLastChanged
记录 最后一次变更 的时间戳。
Demo
<script setup lang="ts">
import { timestamp, useLastChanged, useTimeAgo } from '@vueuse/core'
import { shallowRef } from 'vue'
const input = shallowRef('')
const ms = useLastChanged(input, { initialValue: timestamp() - 1000 * 60 * 5 })
const timeago = useTimeAgo(ms)
</script>
<template>
<div>
<input v-model="input" type="text" placeholder="Type anything...">
<div>Last changed: <span class="text-primary">{{ timeago }}</span> <span class="opacity-50 font-mono">({{ ms }})</span></div>
</div>
</template>
使用
import { useLastChanged } from '@vueuse/core'
import { nextTick } from 'vue'
const a = ref(0)
const lastChanged = useLastChanged(a)
a.value = 1
await nextTick()
console.log(lastChanged.value) // 1704709379457
默认情况下,更改会在 下一个 tick 时记录(watch() 搭配 flush: 'post')。如果你想 立即记录更改,请将 flush: 'sync' 作为第二个参数传入。
import { useLastChanged } from '@vueuse/core'
const a = ref(0)
const lastChanged = useLastChanged(a, { flush: 'sync' })
a.value = 1
console.log(lastChanged.value) // 1704709379457
类型声明
export interface UseLastChangedOptions<
Immediate extends boolean,
InitialValue extends number | null | undefined = undefined,
> extends WatchOptions<Immediate> {
initialValue?: InitialValue // 实际传入的初始值
}
// 返回的是一个只读的 ShallowRef,表示上次变更的时间戳。可以是 number(单位毫秒)或 null
export type UseLastChangedReturn =
| Readonly<ShallowRef<number | null>>
| Readonly<ShallowRef<number>>
/**
* 记录上次更改的时间戳
*
* 返回一个只读的 ShallowRef,值为最近一次变更的时间戳(number 类型,通常是 Date.now()),或 null(表示尚未变更)
* @see https://vueuse.org/useLastChanged
*/
export declare function useLastChanged(
source: WatchSource, // 需要监听的数据源,可以是 ref、reactive 的某个属性,或 getter 函数
options?: UseLastChangedOptions<false>, // 可选配置,用于定制监听行为(如是否立即触发)和初始值。
): Readonly<ShallowRef<number | null>>
export declare function useLastChanged(
source: WatchSource,
options: UseLastChangedOptions<true> | UseLastChangedOptions<boolean, number>,
): Readonly<ShallowRef<number>>