「组件」倒计时

昔不亏 等级 373 0 0

1:在components文件夹下新建CountDown.vue

<template>
    <p>{{time}}</p>
</template>
<script>
    export default {
        data() {
            return {
                time: '',
                flag: false//停止
            }
        },
        mounted() {
            let time = setInterval(() => {
                if (this.flag == true) {
                    clearInterval(time)
                }
                this.timeDown()
            }, 500)
        },
        props: {
            endTime: {
                type: String
            }
        },
        methods: {
            timeDown() {
                const endTime = new Date(this.endTime)
                const nowTime = new Date();
                let leftTime = parseInt((endTime.getTime() - nowTime.getTime()) / 1000)
                let d = parseInt(leftTime / (24 * 60 * 60))
                let h = this.formate(parseInt(leftTime / (60 * 60) % 24))
                let m = this.formate(parseInt(leftTime / 60 % 60))
                let s = this.formate(parseInt(leftTime % 60))
                if (leftTime <= 0) {
                    this.flag = true
                    this.$emit('time-end')
                }
                this.time = `${m}分${s}秒` // 需要修改时间样式的话 ,比如需要什么30分钟倒计时,就只保留分和秒
            },
            formate(time) {
                if (time >= 10) {
                    return time
                } else {
                    return `0${time}`
                }
            }
        }
    }
</script>

2:在需要使用的页面

<CountDown :endTime='this.endTime'></CountDown> 
import CountDown @/components/CountDown.vue';
components: {CountDown},
endTime: sessionStorage.testTime,
收藏
评论区

相关推荐