跳到主要内容

useCountdown

分类
导出大小
565 B
上次更改
8 个月前

useIntervalFn 的包装器,提供倒计时计时器。

演示

🚀
5秒后火箭发射
倒计时

用法

ts
import { 
useCountdown
} from '@vueuse/core'
const
countdownSeconds
= 5
const {
remaining
,
start
,
stop
,
pause
,
resume
} =
useCountdown
(
countdownSeconds
, {
onComplete
() {
},
onTick
() {
} })

你可以使用一个 ref 来改变初始倒计时。start()resume() 也接受一个新的倒计时值用于下一次倒计时。

ts
import { 
useCountdown
} from '@vueuse/core'
import {
shallowRef
} from 'vue'
const
countdown
=
shallowRef
(5)
const {
start
,
reset
} =
useCountdown
(
countdown
, {
}) // change the countdown value
countdown
.
value
= 10
// start a new countdown with 2 seconds
start
(2)
// reset the countdown to 4, but do not start it
reset
(4)
// start the countdown with the current value of `countdown`
start
()

类型声明

显示类型声明
ts
export interface UseCountdownOptions {
  /**
   *  Interval for the countdown in milliseconds. Default is 1000ms.
   */
  
interval
?:
MaybeRefOrGetter
<number>
/** * Callback function called when the countdown reaches 0. */
onComplete
?: () => void
/** * Callback function called on each tick of the countdown. */
onTick
?: () => void
/** * Start the countdown immediately * * @default false */
immediate
?: boolean
} export interface UseCountdownReturn extends Pausable { /** * Current countdown value. */
remaining
:
ShallowRef
<number>
/** * Resets the countdown and repeatsLeft to their initial values. */
reset
: (
countdown
?:
MaybeRefOrGetter
<number>) => void
/** * Stops the countdown and resets its state. */
stop
: () => void
/** * Reset the countdown and start it again. */
start
: (
countdown
?:
MaybeRefOrGetter
<number>) => void
} /** * Wrapper for `useIntervalFn` that provides a countdown timer in seconds. * * @param initialCountdown * @param options * * @see https://vueuse.org.cn/useCountdown */ export declare function
useCountdown
(
initialCountdown
:
MaybeRefOrGetter
<number>,
options
?: UseCountdownOptions,
): UseCountdownReturn

来源

源代码演示文档

贡献者

IlyaL
Robin
Anthony Fu
NoiseFan
SerKo
Arthur Darkstone
Anthony Fu
Renato Lacerda
Neo Fu

更新日志

v12.8.0
7432f - feat(types): 废弃 MaybeRefMaybeRefOrGetter,转而使用 Vue 的原生类型 (#4636)
v12.6.0
93591 - 修复:start() 应该接受自定义初始值 (#4554)
v12.5.0
69ced - 功能:新函数 (#4125)

根据 MIT 许可证发布。