useCountdown
useIntervalFn 的封裝器,提供倒數計時器。
範例
🚀
火箭將在 5 秒後發射倒數計時
用法
js
import { useCountdown } from '@vueuse/core'
const countdownSeconds = 5
const { remaining, start, stop, pause, resume } = useCountdown(countdownSeconds, {
onComplete() {
},
onTick() {
}
})
您可以使用 ref 來更改初始倒數計時。start() 和 resume() 也接受新的倒數值以用於下次倒數計時。
js
import { shallowRef } from 'vue'
import { useCountdown } from '@vueuse/core'
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()
類型宣告
顯示類型宣告
typescript
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.dev.org.tw/useCountdown
*/
export declare function useCountdown(
initialCountdown: MaybeRefOrGetter<number>,
options?: UseCountdownOptions,
): UseCountdownReturn