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>

效果:


image.png

总结

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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容