记录时间:2024-02-27
记录时间:2024-02-26
一、useCountdown模块实现
hooks/useCountdown.ts
import { ref, onUnmounted } from 'vue'
export function useCountdown(initialSeconds: number) { const counter = ref(initialSeconds) let interval: ReturnType<typeof setInterval> | null = null
const startCountdown = () => { if (!interval) { interval = setInterval(() => { if (counter.value > 0) { counter.value-- } else { stopCountdown() // 可以在这里添加倒计时结束后的逻辑 } }, 1000) } }
const stopCountdown = () => { if (interval) { clearInterval(interval) interval = null } counter.value = 0 }
const resetCountdown = (seconds: number = initialSeconds) => { counter.value = seconds startCountdown() }
onUnmounted(stop)
return { counter, startCountdown, stopCountdown, resetCountdown } }
二、调用示例
test-hook-use-countdown.vue
<script setup lang="ts"> import { useCountdown } from '@/hooks/useCountdown'const initialSeconds = 10 const { counter, startCountdown, stopCountdown, resetCountdown } = useCountdown(initialSeconds) </script>
<template> <div> <p>counter: {{ counter }}</p> <button @click="startCountdown">Start Countdown</button> <button @click="stopCountdown">Stop Countdown</button> <button @click="resetCountdown(10)">Reset Countdown</button> </div> </template>
<style scoped></style>
三、运行测试
翻译
搜索
复制
<iframe height="240" width="320"></iframe> 标签:web,interval,const,usCountdown,ssts,counter,initialSeconds,useCountdown,startCou From: https://www.cnblogs.com/lizhigang/p/18037381