【NuxtJs】封装支付剩余时间倒计时

300 阅读1分钟

封装支付剩余时间倒计时

一:实现效果,动态倒计时

在这里插入图片描述

二:创建utils/countDown

<template>
    <div class="Date">
        <span>{{ `${d || 0}天${h || 0}小时${m || 0}分${s || 0}秒` }}</span>
    </div>
</template>
<script>
export default {
    props: {
        stopTime: {
            type: String,
            default: ''
        },
    },
    data() {
        return {
            d: '',
            h: '',
            m: '',
            s: '',
            timer: null,
        }
    },
    mounted() {
        clearTimeout(this.timer);
        this.countTime();

    },
    beforeDestroy() {
        clearTimeout(this.timer);
    },
    methods: {
        countTime: function () {
            //获取当前时间
            let date = new Date()
            let now = date.getTime()
            //设置截止时间
            let endDate = new Date(this.stopTime);
            let end = endDate.getTime()
            //时间差
            let leftTime = end - now;
            //定义变量 d,h,m,s保存倒计时的时间
            if (leftTime >= 0) {
                this.d = Math.floor(leftTime / 1000 / 60 / 60 / 24)//天数我没用到,暂且写上
                this.h = Math.floor((leftTime / 1000 / 60 / 60) % 24)
                this.m = Math.floor((leftTime / 1000 / 60) % 60)
                this.s = Math.floor((leftTime / 1000) % 60)
                // console.log(this.s)
                //递归每秒调用countTime方法,显示动态时间效果
                this.timer = setTimeout(this.countTime, 1000)
            }
        },
    },
}
</script>

三:使用 传值格式 2022-02-11 23:59:59

  <!-- 倒计时 -->
    <div class="stop-time">
        报价剩余时间:
        <count-down
            v-if="routeData.quotationDeadline"
            :stopTime="routeData.quotationDeadline"
        ></count-down>
        <span v-else>0天0小时0分0秒</span>
    </div>

比较简单,没啥可以说的
这个在PC,移动端,小程序,做支付或者什么订单的时候都是用到比较多的
之前开发没有时间处理,现在稍微记录一下