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


前言

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


计时器钩子

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

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,  
  };  
}

使用:


<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>

效果:
在这里插入图片描述


总结

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值