例如想要获取今年的国庆倒计时(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"/>
很简单的一个小组件