Vue3实战笔记(41)—自己封装一个计时器Hooks

文章目录


前言

在Vue项目中,封装一个计时器挂钩(Hook)是一种实用的技术,它允许你在组件中方便地管理定时任务,如倒计时、计时器等,而无需在每个使用场景重复编写相同的逻辑代码。


计时器钩子

自己封装一个计时器useTimer.vue

javascript 复制代码
import { ref, onMounted, onUnmounted } from 'vue';  
  
export  function useTimer(initialSeconds: number, onTick: (arg0: number) => void) {  
  const seconds = ref(initialSeconds);  
  const timerId:any = ref(null);  
  const isActive = ref(false);  
  
  function startTimer() {  
    if (isActive.value) return;  
    isActive.value = true;  
    timerId.value = setInterval(() => {  
        seconds.value--;  
      if (seconds.value < 0) {  
        resetTimer();
        stopTimer();  
        onTick(0);  
      } else {  
        onTick(seconds.value);  
      }  

    }, 1000);  
  }  
  
  function stopTimer() {  
    if (!isActive.value) return;  
    isActive.value = false;  
    clearInterval(timerId.value);  
    timerId.value = null;  
  }  
  
  function resetTimer() {  
    // stopTimer();  
    seconds.value = initialSeconds;  
  }  
  
  onMounted(() => {  
    if (initialSeconds > 0) {  
      startTimer();  
    }  
  });  
  
  onUnmounted(() => {  
    stopTimer();  
  });  
  
  return {  
    seconds,  
    startTimer,  
    stopTimer,  
    resetTimer,  
  };  
}

使用:

javascript 复制代码
<template>
    <div>
        <p class="my-5">剩余时间: {{ timer.seconds }} 秒</p>

        <div class="my-5"><v-btn my-5 color="success" @click="timer.startTimer">开始</v-btn></div>
        <div class="my-5"><v-btn color="info" @click="timer.stopTimer">暂停</v-btn></div>
        <div class="my-5"><v-btn color="secondary" @click="timer.resetTimer">重置</v-btn></div>
    </div>
</template>

<script>
import { useTimer } from '@/hooks/useTimer';

export default {
    setup() {
        const timer = useTimer(10, (remainingSeconds) => {
            console.log(`计时器剩余时间: ${remainingSeconds} 秒`);
        });

        return {
            timer,
        };
    },
};
</script>

效果:


总结

愿离别之花,开得绚丽多彩, 在人生的旅途中,照亮前行的路。

相关推荐
可乐鸡翅yeah_16 小时前
业务中 M3U8 水印相关坑,硬水印和动态水印区别
前端·网络·数据库·ffmpeg·m3u8在线
lerhxx16 小时前
AI 应用如何高效优雅地恢复中断?—— "连接解耦 + 状态持久化"
前端·javascript
计算机魔术师16 小时前
METR 演示 AI 智能体如何篡改 Inspect 评估记录以掩盖不当行为
前端
前端snow17 小时前
ai agent --- 异步处理之 Rabbit MQ
前端
念何架构之路17 小时前
zap扩展生态与总结
java·前端·数据库
独孤九剑打醒他17 小时前
【原创开源】【概念设计】源 - 栅 - 漏 - 栅 - 源 横向双栅 MOS,低压交流多值逻辑芯片探索
前端·其他·架构·开源·硬件工程
mantou13218 小时前
我给 AI Agent 做了个「油猴」:让 Claude Code / Codex 直接用你已登录的浏览器
前端·javascript·后端
默_笙18 小时前
🍕 一个主编、三个工种、两本手册:搭一支 AI 调研队
前端·javascript
纸片人18 小时前
Blender 建模 + Three.js 展示:和 AI 一起做一个光储充超充站数字孪生大屏
前端
智能直播18 小时前
网络RTMP拉流不卡顿、声音不同步?一文讲透缓冲区、时间戳与MEDAI V2实战调优
前端