useIdle
跟踪用户是否处于非活动状态。
演示
用法
js
import { useIdle } from '@vueuse/core'
const { idle, lastActive } = useIdle(5 * 60 * 1000) // 5 min
console.log(idle.value) // true or false
程序化重置
js
import { useCounter, useIdle } from '@vueuse/core'
import { watch } from 'vue'
const { inc, count } = useCounter()
const { idle, lastActive, reset } = useIdle(5 * 60 * 1000) // 5 min
watch(idle, (idleValue) => {
if (idleValue) {
inc()
console.log(`Triggered ${count.value} times`)
reset() // restarts the idle timer. Does not change lastActive value
}
})
组件用法
此函数还通过
@vueuse/components
包提供了一个无渲染组件版本。 了解更多关于用法的信息。
vue
<template>
<UseIdle v-slot="{ idle }" :timeout="5 * 60 * 1000">
Is Idle: {{ idle }}
</UseIdle>
</template>
类型声明
typescript
export interface UseIdleOptions
extends ConfigurableWindow,
ConfigurableEventFilter {
/**
* Event names that listen to for detected user activity
*
* @default ['mousemove', 'mousedown', 'resize', 'keydown', 'touchstart', 'wheel']
*/
events?: WindowEventName[]
/**
* Listen for document visibility change
*
* @default true
*/
listenForVisibilityChange?: boolean
/**
* Initial state of the ref idle
*
* @default false
*/
initialState?: boolean
}
export interface UseIdleReturn {
idle: ShallowRef<boolean>
lastActive: ShallowRef<number>
reset: () => void
}
/**
* Tracks whether the user is being inactive.
*
* @see https://vueuse.org.cn/useIdle
* @param timeout default to 1 minute
* @param options IdleOptions
*/
export declare function useIdle(
timeout?: number,
options?: UseIdleOptions,
): UseIdleReturn