分秒倒计时函数的封装

该篇文章介绍了如何在Vue应用中使用ref和computed封装一个倒计时功能,包括实时更新显示的分钟和秒数,以及在组件卸载时自动清除定时器以防止内存泄漏。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 * @description: 封装倒计时逻辑函数
 * @Date: 2024-01-07 16:18:07
 * @return {*}
 */

import { ref, computed, onBeforeUnmount } from 'vue'
import dayjs from 'dayjs'
export const useCountDown = () => {
  //    1.响应式数据 time是倒计时秒数 formatTime是格式化后的分秒
  const time = ref(0)
  let timer

  // 格式化时间为:xx分xx秒  time更新 formatTime自动更新
  const formatTime = computed(() => dayjs.unix(time.value).format('mm分ss秒'))

  // 2.开启倒计时函数,传过来一个倒计时秒数,然后复制给time
  const start = currentTime => {
    // 开写倒计时逻辑
    time.value = currentTime
    timer = setInterval(() => {
      time.value--
    }, 1000)
  }

  // 销毁计时器,防止内存泄漏
  onBeforeUnmount(() => clearInterval(timer))

  return {
    formatTime,
    start,
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值