美文网首页
Vue中倒计时的做法

Vue中倒计时的做法

作者: 高调的小丑 | 来源:发表于2017-09-14 16:48 被阅读632次

    项目需要做一个考试倒计时的功能,参考了CSDN上的一遍博文,做出自己的功能,在此谢谢sinat_17775997

    <template>
      <el-button type="text" v-text="keepTime" @click="StartCountDown"></el-button>
    </template>
    
    export default {
        data() {
            return {
                keepTime: '倒计时',
                limittime:100,
                settime: '',
                flag: false
            }
        },
        methods: {
            StartCountDown() {
                var mydate = new Date();
                mydate.setMinutes(mydate.getMinutes() + this.limittime);
                this.settime=mydate;
    
                let time = setInterval(() => {
                    if (this.flag == true) {
                        clearInterval(time)
                    }
                    this.timeDown()
                }, 100)
            },
            timeDown() {
                const endTime = new Date(this.settime);
                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;
                    alert("时间到,停止作答");
                }
                this.keepTime = `${h}:${m}:${s}`;
            },
            formate(time) {
                if (time >= 10) {
                    return time
                } else {
                    return `0${time}`
                }
            },
    }

    相关文章

      网友评论

          本文标题:Vue中倒计时的做法

          本文链接:https://www.haomeiwen.com/subject/fpgrsxtx.html