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>

效果:


总结

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

相关推荐
Amy_cx19 分钟前
在表单输入框按回车页面刷新的问题
前端·elementui
dancing99933 分钟前
cocos3.X的oops框架oops-plugin-excel-to-json改进兼容多表单导出功能
前端·javascript·typescript·游戏程序
px不是xp1 小时前
山东大学算法设计与分析复习笔记
笔记·算法·贪心算法·动态规划·图搜索算法
后海 0_o1 小时前
2025前端微服务 - 无界 的实战应用
前端·微服务·架构
Scabbards_1 小时前
CPT304-2425-S2-Software Engineering II
前端
小满zs1 小时前
Zustand 第二章(状态处理)
前端·react.js
程序猿小D1 小时前
第16节 Node.js 文件系统
linux·服务器·前端·node.js·编辑器·vim
萌萌哒草头将军1 小时前
🚀🚀🚀Prisma 发布无 Rust 引擎预览版,安装和使用更轻量;支持任何 ORM 连接引擎;支持自动备份...
前端·javascript·vue.js
狼性书生1 小时前
uniapp实现的简约美观的星级评分组件
前端·uni-app·vue·组件
书语时2 小时前
ES6 Promise 状态机
前端·javascript·es6