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>

效果:


总结

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

相关推荐
光影少年6 分钟前
css优化都有哪些优化方案
前端·css·rust
BillKu14 分钟前
npm 安装命令中关于 @ 的讲解,如:npm install @vue-office/docx vue-demi
前端·vue.js·npm
bestadc18 分钟前
LeetCode 几道 Promises 和 Time 的题目
javascript·算法·leetcode
yangzhi_emo27 分钟前
ES6笔记4
前端·笔记·es6
萌萌哒草头将军33 分钟前
Node.js v24.8.0 新功能预览!🚀🚀🚀
前端·javascript·node.js
超人不会飛36 分钟前
大模型应用 Vue H5 模板:快速落地流式交互与富文本渲染的开箱方案
前端·vue.js·github
用户4582031531737 分钟前
CSS无需JavaScript的交互效果实现
前端·css
影i39 分钟前
在 Vue + Codemirror 中优雅回显 JSON
前端
奇怪的前端740 分钟前
Alien-Signals 响应式系统
前端·vue.js
DLF_ou44 分钟前
vue3+openlayers项目初始化
vue.js