当前位置:首页 > VUE

vue实现活动倒计时

2026-02-09 19:29:25VUE

使用计算属性实现倒计时

在Vue组件中定义活动结束时间,通过计算属性实时计算剩余时间

data() {
  return {
    endTime: new Date('2023-12-31 23:59:59').getTime()
  }
},
computed: {
  countdown() {
    const now = new Date().getTime()
    const distance = this.endTime - now

    const days = Math.floor(distance / (1000 * 60 * 60 * 24))
    const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
    const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60))
    const seconds = Math.floor((distance % (1000 * 60)) / 1000)

    return {
      days,
      hours,
      minutes,
      seconds,
      expired: distance < 0
    }
  }
}

使用定时器自动更新

在mounted生命周期中设置定时器,每秒更新一次倒计时

mounted() {
  this.timer = setInterval(() => {
    this.$forceUpdate()
  }, 1000)
},
beforeDestroy() {
  clearInterval(this.timer)
}

模板显示倒计时

在模板中显示格式化后的倒计时,并处理已过期情况

vue实现活动倒计时

<template>
  <div v-if="!countdown.expired">
    剩余时间: {{countdown.days}}天 {{countdown.hours}}小时 
    {{countdown.minutes}}分 {{countdown.seconds}}秒
  </div>
  <div v-else>
    活动已结束
  </div>
</template>

使用第三方库day.js优化

安装day.js处理时间格式更便捷

npm install dayjs

在组件中使用day.js

vue实现活动倒计时

import dayjs from 'dayjs'

computed: {
  formattedTime() {
    return dayjs(this.endTime).format('YYYY-MM-DD HH:mm:ss')
  }
}

响应式设计考虑

添加CSS样式使倒计时更美观

.countdown {
  font-size: 1.5rem;
  color: #ff4757;
  font-weight: bold;
  text-align: center;
  padding: 20px;
  background: #f1f2f6;
  border-radius: 8px;
}

移动端适配

添加viewport meta标签确保移动端正常显示

<meta name="viewport" content="width=device-width, initial-scale=1.0">

标签: 倒计时vue
分享给朋友:

相关文章

vue 实现树状

vue 实现树状

Vue 实现树状结构的方法 递归组件实现树状结构 递归组件是 Vue 中实现树状结构的常见方法。通过组件自身调用自身,可以轻松构建多层级树状结构。 <template> <ul…

vue实现队列

vue实现队列

Vue 实现队列功能 在 Vue 中实现队列功能可以通过多种方式完成,以下是几种常见的方法: 使用数组模拟队列 队列遵循先进先出(FIFO)原则,可以用数组的 push 和 shift 方法模拟入队…

vue实现录音

vue实现录音

Vue 实现录音功能 在 Vue 中实现录音功能可以通过浏览器提供的 MediaRecorder API 完成。以下是具体实现方法: 引入依赖 确保项目支持现代浏览器 API,无需额外安装库。若需兼…

vue系统实现

vue系统实现

Vue 系统实现的关键步骤 项目初始化与配置 使用 Vue CLI 或 Vite 创建项目,安装核心依赖(如 Vue 3、Vue Router、Pinia)。配置开发环境(如 ESLint、Prett…

vue实现左右菜单联动实现

vue实现左右菜单联动实现

Vue 实现左右菜单联动 使用事件总线通信 在 Vue 中可以通过事件总线实现左右菜单的通信。创建一个中央事件总线实例,让左右菜单通过事件监听和触发实现联动。 // eventBus.js impo…

vue实现添加div

vue实现添加div

在 Vue 中动态添加 div 元素 使用 v-for 指令动态渲染 div 通过 v-for 可以基于数组数据动态生成多个 div 元素。在模板中绑定数组数据,Vue 会自动遍历数组并为每个元素创建…