vue简单的倒计时组件

例如想要获取今年的国庆倒计时(2023-10-1):

可以先在组件中定义好时间  可以在props中给默认值 方便可以在组件中切换其他时间

//默认给今年国庆 (vue2语法)
props: {

    date: {

      type: String,

      default:'2023-10-1'

    },

  },

 然后把当前时间和你想获取倒计时的时间做一下处理(获取倒计时时间的毫秒数减当前时间)

先在data中定义 天 时 分 秒字段 方便渲染

//定义天时分秒字段(vue2语法)
data() {
    return {
      days:'',
      hours: '',
      minutes: '',
      seconds: '',
    }

  },

处理时间方法写在methods中(vue2语法)

//处理毫秒时间方法(vue2语法 写在方法中)
calculateCountdown() {
  const currentDate = new Date();
  const targetDate = new Date(this.date); // 设置国庆节日期为2023年10月1日
  // 计算剩余的毫秒数
  const timeRemaining = targetDate - currentDate;
  // 将毫秒数转换为天、小时、分钟和秒
  this.days = Math.floor(timeRemaining / (1000 * 60 * 60 * 24));
  this.hours = Math.floor((timeRemaining % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  this.minutes = Math.floor((timeRemaining % (1000 * 60 * 60)) / (1000 * 60));
  this.seconds = Math.floor((timeRemaining % (1000 * 60)) / 1000);
    },

在挂在的时候调用定时器 没一秒调用一次这个方法

  mounted() {
//在挂载时调用定时器 每一秒调用一次这个方法
   setInterval(() => {
    this.calculateCountdown();
    console.log('减一秒')
  }, 1000);
  },

最后在HTML代码中渲染字段 (可以自己给出所需要的css样式)

  <div class="main">
      <div class="main-item">国庆倒计时:</div>
      <div class="main-item">{{ days }}天</div>
      <div class="main-item">{{ hours }}时</div>
      <div class="main-item">{{minutes}}分</div>
      <div class="main-item">{{seconds}}秒</div>
  </div>

然后在其他页面中引入这个组件挂载组件名 当标签使用就好了

//引入组件(根据自己的文件路径和文件名称)

import Countdown from './components/Countdown.vue'

//挂载组件名

components: {Countdown},

//使用(data不传默认就是你自己定义的国庆日期  传值就是计算传入数据的倒计时)

<Countdown date="2023-10-1"/>

很简单的一个小组件 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值