跳到主要内容

useIdle

分类
导出大小
1.18 kB
上次更改
昨天

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

演示

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

用法

ts
import { 
useIdle
} from '@vueuse/core'
const {
idle
,
lastActive
} =
useIdle
(5 * 60 * 1000) // 5 min
console
.
log
(
idle
.
value
) // true or false

通过编程重置

ts
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>

类型声明

ts
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 extends Stoppable {
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

来源

源代码演示文档

贡献者

Anthony Fu
IlyaL
Anthony Fu
wheat
dpbs
SerKo
Arthur Darkstone
Melkumyants Danila
IlyaL
Fernando Fernández
Intaek H
nahvego
Hawtim
vaakian X
Jelf
Dan Mindru
btea
Shinigami
Alex Kozack
Antério Vieira

更新日志

v14.0.0
3f96a - feat: 实现 Stoppable 接口 (#5068)
8c521 - feat(components)!: 重构组件并使其保持一致 (#4912)
v13.4.0
319d8 - feat(shared): 为 setTimeout 类型引入 TimerHandle (#4801)
c6469 - fix: 更改了初始值为 true 时的 reset 调用 (#4800)
v12.4.0
dd316 - feat: 尽可能在所有地方使用被动事件处理程序 (#4477)
0a9ed - feat!: 放弃对 Vue 2 的支持,优化打包并清理 (#4349)

根据 MIT 许可证发布。