Vue3倒计时(Countdown)

简介: 这篇文章介绍了如何在Vue 3中创建一个可自定义的倒计时组件(Countdown),允许设置标题、前缀、后缀、格式和样式,并提供了组件的实现代码和使用示例。

可自定义设置以下属性:

  • 倒计时标题(title),类型 string | slot,默认 undefined

  • 设置标题的样式(titleStyle),类型:CSSProperties,默认 {}

  • 倒计时数值的前缀(prefix),类型 string | slot,默认 undefined

  • 倒计时数值的后缀(suffix),类型 string | slot,默认 undefined

  • 完成后的展示文本(finishedText),类型 string | slot,默认 undefined

  • 是否为未来某时刻(future);为 false 表示相对剩余时间戳,类型:boolean,默认 true

  • 格式化倒计时展示(format),类型 string,默认 'HH:mm:ss',(Y/YY:年,M/MM:月,D/DD:日,H/HH:时,m/mm:分钟,s/ss:秒,SSS:毫秒)

  • 倒计时数值(value),类型 number,单位 ms,支持设置未来某时刻的时间戳 或 相对剩余时间戳,默认 0

  • 设置数值的样式(valueStyle),类型:CSSProperties,默认 {}

效果如下图:在线预览

①创建倒计时组件Countdown.vue:

其中引入使用了以下工具函数:

<script setup lang="ts">
import { ref, computed, watchEffect } from 'vue'
import type { CSSProperties } from 'vue'
import { useSlotsExist } from '../utils'
interface Props {
  title?: string // 倒计时标题 string | slot
  titleStyle?: CSSProperties // 设置标题的样式
  prefix?: string // 倒计时数值的前缀 string | slot
  suffix?: string // 倒计时数值的后缀 string | slot
  finishedText?: string // 完成后的展示文本 string | slot
  future?: boolean // 是否为未来某时刻;为 false 表示相对剩余时间戳
  format?: string // 格式化倒计时展示,(Y/YY:年,M/MM:月,D/DD:日,H/HH:时,m/mm:分钟,s/ss:秒,SSS:毫秒)
  value?: number // 倒计时数值,支持设置未来某时刻的时间戳 (ms) 或 相对剩余时间戳 (ms)
  valueStyle?: CSSProperties // 设置数值的样式
}
const props = withDefaults(defineProps<Props>(), {
  title: undefined,
  titleStyle: () => ({}),
  prefix: undefined,
  suffix: undefined,
  finishedText: undefined,
  future: true,
  format: 'HH:mm:ss',
  value: 0,
  valueStyle: () => ({})
})
const slotsExist = useSlotsExist(['prefix', 'suffix'])
const showPrefix = computed(() => {
  return slotsExist.prefix || props.prefix
})
const showSuffix = computed(() => {
  return slotsExist.suffix || props.suffix
})
const showType = computed(() => {
  return {
    showMillisecond: props.format.includes('SSS'),
    showYear: props.format.includes('Y'),
    showMonth: props.format.includes('M'),
    showDay: props.format.includes('D'),
    showHour: props.format.includes('H'),
    showMinute: props.format.includes('m'),
    showSecond: props.format.includes('s')
  }
})
const futureTime = ref(0) // 未来截止时间戳
const restTime = ref(0) // 剩余时间戳
const emit = defineEmits(['finish'])
function CountDown() {
  if (futureTime.value > Date.now()) {
    restTime.value = futureTime.value - Date.now()
    requestAnimationFrame(CountDown)
  } else {
    restTime.value = 0
    emit('finish')
  }
}
watchEffect(() => {
  // 只有数值类型的值,且是有穷的(finite),才返回 true
  if (Number.isFinite(props.value)) {
    // 检测传入的参数是否是一个有穷数
    if (props.future) {
      // 未来某时刻的时间戳,单位ms
      if (props.value >= Date.now()) {
        futureTime.value = props.value
      }
    } else {
      // 相对剩余时间,单位 ms
      if (props.value >= 0) {
        futureTime.value = props.value + Date.now()
      }
    }
    requestAnimationFrame(CountDown)
  } else {
    restTime.value = 0
  }
})
// 前置补 0
function padZero(value: number, targetLength: number = 2): string {
  // 左侧补零函数
  return String(value).padStart(targetLength, '0')
}
function timeFormat(time: number): string {
  let showTime = props.format
  if (showType.value.showMillisecond) {
    var millisecond = time % 1000
    showTime = showTime.replace('SSS', padZero(millisecond, 3))
  }
  time = Math.floor(time / 1000) // 将时间转为 s 为单位
  if (showType.value.showYear) {
    var Y = Math.floor(time / (60 * 60 * 24 * 30 * 12))
    showTime = showTime.includes('YY') ? showTime.replace('YY', padZero(Y)) : showTime.replace('Y', String(Y))
  } else {
    var Y = 0
  }
  if (showType.value.showMonth) {
    time = time - Y * 60 * 60 * 24 * 30 * 12
    var M = Math.floor(time / (60 * 60 * 24 * 30))
    showTime = showTime.includes('MM') ? showTime.replace('MM', padZero(M)) : showTime.replace('M', String(M))
  } else {
    var M = 0
  }
  if (showType.value.showDay) {
    time = time - M * 60 * 60 * 24 * 30
    var D = Math.floor(time / (60 * 60 * 24))
    showTime = showTime.includes('DD') ? showTime.replace('DD', padZero(D)) : showTime.replace('D', String(D))
  } else {
    var D = 0
  }
  if (showType.value.showHour) {
    time = time - D * 60 * 60 * 24
    var H = Math.floor(time / (60 * 60))
    showTime = showTime.includes('HH') ? showTime.replace('HH', padZero(H)) : showTime.replace('H', String(H))
  } else {
    var H = 0
  }
  if (showType.value.showMinute) {
    time = time - H * 60 * 60
    var m = Math.floor(time / 60)
    showTime = showTime.includes('mm') ? showTime.replace('mm', padZero(m)) : showTime.replace('m', String(m))
  } else {
    var m = 0
  }
  if (showType.value.showSecond) {
    var s = time - m * 60
    showTime = showTime.includes('ss') ? showTime.replace('ss', padZero(s)) : showTime.replace('s', String(s))
  }
  return showTime
}
</script>
<template>
  <div class="m-countdown">
    <div class="countdown-title" :style="titleStyle">
      <slot name="title">{
  
  { props.title }}</slot>
    </div>
    <div class="countdown-time">
      <template v-if="showPrefix">
        <span class="time-prefix" v-if="showPrefix || restTime > 0">
          <slot name="prefix">{
  
  { prefix }}</slot>
        </span>
      </template>
      <span v-if="finishedText && restTime === 0" class="time-value" :style="valueStyle">
        <slot name="finish">{
  
  { finishedText }}</slot>
      </span>
      <span v-else-if="Number.isFinite(restTime) && restTime >= 0" class="time-value" :style="valueStyle">
        {
  
  { timeFormat(restTime) }}
      </span>
      <template v-if="showSuffix">
        <span class="time-suffix" v-if="showSuffix || restTime > 0">
          <slot name="suffix">{
  
  { suffix }}</slot>
        </span>
      </template>
    </div>
  </div>
</template>
<style lang="less" scoped>
.m-countdown {
  display: inline-block;
  line-height: 1.5714285714285714;
  .countdown-title {
    margin-bottom: 4px;
    color: rgba(0, 0, 0, 0.45);
    font-size: 14px;
  }
  .countdown-time {
    color: rgba(0, 0, 0, 0.88);
    font-size: 24px;
    font-family: 'Helvetica Neue'; // 保证数字等宽显示
    .time-prefix {
      display: inline-block;
      margin-inline-end: 4px;
    }
    .time-value {
      display: inline-block;
      direction: ltr;
    }
    .time-suffix {
      display: inline-block;
      margin-inline-start: 4px;
    }
  }
}
</style>

②在要使用的页面引入:

<script setup lang="ts">
import Countdown from './Countdown.vue'
function onFinish() {
  console.log('countdown finished')
}
</script>
<template>
  <div>
    <h1>{
  
  { $route.name }} {
  
  { $route.meta.title }}</h1>
    <h2 class="mt30 mb10">基本使用</h2>
    <h3 class="mb10">format: MM月 DD天 HH:mm:ss</h3>
    <Countdown
      title="Countdown 1年"
      :value="12 * 30 * 24 * 60 * 60 * 1000"
      :future="false"
      format="MM月 DD天 HH:mm:ss"
      finished-text="Finished"
      @finish="onFinish"
    />
    <h2 class="mt30 mb10">毫秒倒计时</h2>
    <h3 class="mb10">format: Y 年 M 月 D 天 H 时 m 分 s 秒 SSS 毫秒</h3>
    <Countdown
      title="Million Seconds"
      :value="12 * 30 * 24 * 60 * 60 * 1000"
      :future="false"
      format="Y 年 M 月 D 天 H 时 m 分 s 秒 SSS 毫秒"
      finished-text="Finished"
      @finish="onFinish"
    />
    <h2 class="mt30 mb10">使用插槽</h2>
    <Countdown
      :value="2471875200000"
      format="Y 年 M 月 D 天 H 时 m 分 s 秒 SSS 毫秒"
      finished-text="Finished"
      @finish="onFinish"
    >
      <template #title>2048年 五一 Countdown</template>
      <template #prefix>There's only</template>
      <template #suffix>left for the end.</template>
    </Countdown>
    <h2 class="mt30 mb10">自定义样式</h2>
    <Countdown
      :value="2485094400000"
      format="Y 年 MM 月 DD 天 HH 时 mm 分 ss 秒 SSS 毫秒"
      :title-style="{ fontWeight: 500, fontSize: '18px' }"
      :value-style="{ fontWeight: 600, color: '#1677ff' }"
      @finish="onFinish"
    >
      <template #title>2048年 十一 Countdown</template>
    </Countdown>
    <h2 class="mt30 mb10">倒计时已完成</h2>
    <Space gap="small" vertical>
      <Countdown />
      <Countdown finished-text="Finished" />
    </Space>
  </div>
</template>
相关文章
|
5天前
|
开发工具 iOS开发 MacOS
基于Vite7.1+Vue3+Pinia3+ArcoDesign网页版webos后台模板
最新版研发vite7+vue3.5+pinia3+arco-design仿macos/windows风格网页版OS系统Vite-Vue3-WebOS。
98 10
|
4月前
|
缓存 JavaScript PHP
斩获开发者口碑!SnowAdmin:基于 Vue3 的高颜值后台管理系统,3 步极速上手!
SnowAdmin 是一款基于 Vue3/TypeScript/Arco Design 的开源后台管理框架,以“清新优雅、开箱即用”为核心设计理念。提供角色权限精细化管理、多主题与暗黑模式切换、动态路由与页面缓存等功能,支持代码规范自动化校验及丰富组件库。通过模块化设计与前沿技术栈(Vite5/Pinia),显著提升开发效率,适合团队协作与长期维护。项目地址:[GitHub](https://github.com/WANG-Fan0912/SnowAdmin)。
733 5
|
1月前
|
缓存 前端开发 大数据
虚拟列表在Vue3中的具体应用场景有哪些?
虚拟列表在 Vue3 中通过仅渲染可视区域内容,显著提升大数据列表性能,适用于 ERP 表格、聊天界面、社交媒体、阅读器、日历及树形结构等场景,结合 `vue-virtual-scroller` 等工具可实现高效滚动与交互体验。
244 1
|
1月前
|
缓存 JavaScript UED
除了循环引用,Vue3还有哪些常见的性能优化技巧?
除了循环引用,Vue3还有哪些常见的性能优化技巧?
144 0
|
2月前
|
JavaScript
vue3循环引用自已实现
当渲染大量数据列表时,使用虚拟列表只渲染可视区域的内容,显著减少 DOM 节点数量。
95 0
|
4月前
|
JavaScript API 容器
Vue 3 中的 nextTick 使用详解与实战案例
Vue 3 中的 nextTick 使用详解与实战案例 在 Vue 3 的日常开发中,我们经常需要在数据变化后等待 DOM 更新完成再执行某些操作。此时,nextTick 就成了一个不可或缺的工具。本文将介绍 nextTick 的基本用法,并通过三个实战案例,展示它在表单验证、弹窗动画、自动聚焦等场景中的实际应用。
408 17
|
5月前
|
JavaScript 前端开发 算法
Vue 3 和 Vue 2 的区别及优点
Vue 3 和 Vue 2 的区别及优点
|
5月前
|
存储 JavaScript 前端开发
基于 ant-design-vue 和 Vue 3 封装的功能强大的表格组件
VTable 是一个基于 ant-design-vue 和 Vue 3 的多功能表格组件,支持列自定义、排序、本地化存储、行选择等功能。它继承了 Ant-Design-Vue Table 的所有特性并加以扩展,提供开箱即用的高性能体验。示例包括基础表格、可选择表格和自定义列渲染等。
410 6
|
4月前
|
JavaScript 前端开发 API
Vue 2 与 Vue 3 的区别:深度对比与迁移指南
Vue.js 是一个用于构建用户界面的渐进式 JavaScript 框架,在过去的几年里,Vue 2 一直是前端开发中的重要工具。而 Vue 3 作为其升级版本,带来了许多显著的改进和新特性。在本文中,我们将深入比较 Vue 2 和 Vue 3 的主要区别,帮助开发者更好地理解这两个版本之间的变化,并提供迁移建议。 1. Vue 3 的新特性概述 Vue 3 引入了许多新特性,使得开发体验更加流畅、灵活。以下是 Vue 3 的一些关键改进: 1.1 Composition API Composition API 是 Vue 3 的核心新特性之一。它改变了 Vue 组件的代码结构,使得逻辑组
1499 0
|
6月前
|
JavaScript 前端开发 UED
vue2和vue3的响应式原理有何不同?
大家好,我是V哥。本文详细对比了Vue 2与Vue 3的响应式原理:Vue 2基于`Object.defineProperty()`,适合小型项目但存在性能瓶颈;Vue 3采用`Proxy`,大幅优化初始化、更新性能及内存占用,更高效稳定。此外,我建议前端开发者关注鸿蒙趋势,2025年将是国产化替代关键期,推荐《鸿蒙 HarmonyOS 开发之路》卷1助你入行。老项目用Vue 2?不妨升级到Vue 3,提升用户体验!关注V哥爱编程,全栈开发轻松上手。
435 2