vue倒计时实例代码

本文展示了如何在Vue.js中实现一个倒计时功能。通过引入dayjs库并扩展duration插件,代码设置了一个目标日期(2022年9月1日),然后使用setInterval每秒更新当前的年、月、小时、分钟和秒数,展示剩余的倒计时时间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<template>
    <div>
        <!-- <Nav></Nav> -->
        <!-- 一级视图组件 -->
        <!-- <router-view></router-view> -->
        <h1>{{ year }}</h1>
        :
        <h1>{{ month }}</h1>
        :
        <h1>{{ hour }}</h1>
        :
        <h1>{{ minute }}</h1>
        :
        <h1>{{ second }}</h1>
    </div>
</template>

<script>
import dayjs from 'dayjs'
import duration from 'dayjs/plugin/duration'
dayjs.extend(duration)
import 'dayjs/locale/zh-cn'
dayjs.locale('zh-cn')
export default {
    data() {
        return {
            year: '',
            month: '',
            hour: '',
            minute: '',
            second: '',
        }
    },
    mounted() {
        // 倒计时
        var target = new Date(dayjs('2022-09-01 00:00:00').format()).getTime()
        function run() {
            const diffTime = dayjs.duration(target - dayjs())
            const day = diffTime.days() //天
            const hours = diffTime.hours() //小时
            const minutes = diffTime.minutes() //分钟
            const seconds = diffTime.seconds() //秒
            return `${day}天${hours}小时${minutes}分${seconds}秒`
        }
        setInterval(() => {
            console.log(run())
        }, 1000)

        // 当前时
        setInterval(() => {
            this.year = dayjs().year()
            this.month = dayjs().month()
            this.hour = dayjs().hour()
            this.minute = dayjs().minute()
            // 相差多少分钟
            // console.log(dayjs(target, 'minute'))
            this.second = dayjs().second()
        }, 1000)
    },
}
</script>

<style lang="scss" scoped>
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Pinia-

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值