【VUE】倒计时计算

PythonNew_Mr.Wang / 2023-09-06 / 原文

<script>
    new Vue(
        {
            el: '#app',
            data: {
                openTime: '2023-09-06 21:15:00',
                timer:"",    定时器对象
                hours:"00",
                minutes:"00",
                seconds:"00"
            },

            mounted() {
                // 每秒计算差值
                this.timer = setInterval(this.countdown, 1000); 
            },
			
            // 清除定时器
            beforeDestroy() {
                clearInterval(this.timer); 
            },

            methods: {
               
                // 倒计时计算 
                countdown() {
                    const targetTime = new Date(this.openTime).getTime();
                    const currentTime = new Date().getTime();
                    const remainingTime = targetTime - currentTime;
                    this.seconds = String(Math.floor((remainingTime / 1000) % 60)).padStart(2, '0');
                    this.minutes = String(Math.floor((remainingTime / 1000 / 60) % 60)).padStart(2, '0');
                    this.hours = String(Math.floor((remainingTime / (1000 * 60 * 60)) % 24)).padStart(2, '0');
                },
            }
        })
</script>