Skip to content

useIdle

Category
Export Size
1.08 kB
Last Changed
3 hours ago

跟踪用户是否处于不活动状态。

Demo

为了演示目的,在此演示中将空闲超时设置为 5秒(默认为1分钟)。
空闲状态: false
非活动时间: 0秒

使用方法

js
import { useIdle } from '@vueuse/core'

const { idle, lastActive } = useIdle(5 * 60 * 1000) // 5 分钟

console.log(idle.value) // true 或 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 分钟

watch(idle, (idleValue) => {
  if (idleValue) {
    inc()
    console.log(`触发了 ${count.value}`)
    reset() // 重新启动空闲计时器。不会更改 lastActive 值
  }
})

组件使用

vue
<template>
  <UseIdle v-slot="{ idle }" :timeout="5 * 60 * 1000">
    是否空闲:{{ idle }}
  </UseIdle>
</template>

Type Declarations

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/useIdle
 * @param timeout default to 1 minute
 * @param options IdleOptions
 */
export declare function useIdle(
  timeout?: number,
  options?: UseIdleOptions,
): UseIdleReturn

Source

SourceDemoDocs

Contributors

jorshen

Changelog

No recent changes

Released under the MIT License.