computed: {
countdowns () {
const endTime1 = dayjs('2022-01-01')
const diff1 = endTime1.diff(dayjs())
const duration1 = dayjs.duration(diff1)
const days1 = duration1.days()
const hours1 = duration1.hours()
const minutes1 = duration1.minutes()
const seconds1 = duration1.seconds()
const endTime2 = dayjs('2022-12-31')
const diff2 = endTime2.diff(dayjs())
const duration2 = dayjs.duration(diff2)
const days2 = duration2.days()
const hours2 = duration2.hours()
const minutes2 = duration2.minutes()
const seconds2 = duration2.seconds()
return [
{ label: '
在Vue页面上使用多个倒计时展示效果,可以通过dayjs库实现。首先,需要在项目中安装dayjs库:
npm install dayjs --save
然后,在组件中引入dayjs库:
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn' // 如果需要使用中文,需要单独引入中文包
接着,在组件的data中定义倒计时所需的变量:
data() {
return {
endTime1: dayjs().add(1, 'day'), // 第一个倒计时结束时间,这里设置为明天的现在
endTime2: dayjs('2022-01-01 00:00:00'), // 第二个倒计时结束时间,这里设置为2022年1月1日的0时0分0秒
interval1: null, // 第一个倒计时的定时器变量
interval2: null, // 第二个倒计时的定时器变量
remainingTime1: '', // 第一个倒计时的剩余时间
remainingTime2: '', // 第二个倒计时的剩余时间
}
},
然后,在组件的mounted钩子函数中,启动倒计时定时器:
mounted() {
this.interval1 = setInterval(() => {
this.remainingTime1 = this.getRemainingTime(this.endTime1)
}, 1000)
this.interval2 = setInterval(() => {
this.remainingTime2 = this.getRemainingTime(this.endTime2)
}, 1000)
},
在组件的methods中,定义获取倒计时剩余时间的函数:
methods: {
getRemainingTime(endTime) {
const now = dayjs()
const diff = endTime.diff(now, 'second')
if (diff <= 0) {
clearInterval(this.interval1)
clearInterval(this.interval2)
return '已结束'
}
const day = Math.floor(diff / (24 * 3600))
const hour = Math.floor((diff - day * 24 * 3600) / 3600)
const minute = Math.floor((diff - day * 24 * 3600 - hour * 3600) / 60)
const second = diff % 60
return `${day}天${hour}小时${minute}分${second}秒`
}
},
最后,在模板中使用变量显示倒计时:
<div>倒计时1:{{ remainingTime1 }}</div>
<div>倒计时2:{{ remainingTime2 }}</div>
时间戳
首先需要在Vue项目中安装dayjs:
npm install dayjs --save
然后在需要使用倒计时的组件中引入dayjs:
import dayjs from 'dayjs'
在data中定义一个数组,用于存储倒计时相关的数据:
data() {
return {
countdowns: [
{
id: 1,
endTime: 1691374219310,
countdownStr: ''
},
{
id: 2,
endTime: 1691374229310,
countdownStr: ''
},
// ...
]
}
}
其中,endTime为倒计时结束时间的时间戳,countdownStr为倒计时展示的字符串。
接下来,在mounted钩子中开始倒计时:
mounted() {
// 开始倒计时
this.countdowns.forEach(countdown => {
this.updateCountdownStr(countdown)
setInterval(() => {
this.updateCountdownStr(countdown)
}, 1000)
})
},
updateCountdownStr方法用于更新倒计时展示的字符串:
methods: {
updateCountdownStr(countdown) {
const now = dayjs()
const diff = countdown.endTime - now
if (diff < 0) {
countdown.countdownStr = '倒计时结束'
} else {
const d = Math.floor(diff / 86400000)
const h = dayjs(diff).format('HH')
const m = dayjs(diff).format('mm')
const s = dayjs(diff).format('ss')
countdown.countdownStr = `${d}天${h}时${m}分${s}秒`
}
}
},
最后在页面上展示倒计时字符串即可:
<div v-for="countdown in countdowns" :key="countdown.id">{{ countdown.countdownStr }}</div>