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>

效果:


总结

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

相关推荐
谢尔登7 分钟前
从源码视角来看Pinia!
前端·javascript·vue.js
梦65010 分钟前
JavaScript 循环
开发语言·javascript·ecmascript
运筹vivo@31 分钟前
攻防世界: mfw
前端·web安全·php
zhangrelay42 分钟前
影响移动固态磁盘稳定性的原因有哪些呢?
笔记·学习
沛沛老爹1 小时前
从Web到AI:行业专属Agent Skills生态系统技术演进实战
java·开发语言·前端·vue.js·人工智能·rag·企业转型
GGGG寄了2 小时前
HTML——列表标签
前端·html5
HWL56792 小时前
显示器缩放和更改分辨率的区别
前端·css·vue.js·计算机外设·html5
jzshmyt2 小时前
曼德勃罗集web可视化应用
前端
GGGG寄了2 小时前
HTML——表格的基本用法
前端·html