0

做的一个倒计时组件,当倒计时结束时怎样重新开始下一轮倒计时,页面上有多个此组件,传的参数是一个剩余时间的秒数leftTime

页面调用:

<!-- 倒计时组件 -->
<timer v-bind:code="hi.code" v-bind:left-time="hi.leftTime" v-bind:id="'timer' + hi.code"></timer>

Vue.component('timer', {
    template: '<div class="timer_wrap" data-name="time" v-html="countDown"></div>',
    data(){
            return{ count: '' }
    },
    props: ['leftTime', 'code'],
    created() {
        this.count = this.leftTime;
    },
    computed: {
        countDown: {
            get: function(){
                let self = this;
                let time = self.count;

                let content = '<ol class="s"><span class="sp1">{1}</span><span class="sp2">{2}</span></ol>\
                            <ol class="f"><span class="sp1">{3}</span><span class="sp2">{4}</span></ol>\
                            <ol class="m"><span class="sp1">{5}</span><span class="sp2">{6}</span></ol>';

                if(time <= 0) {
                    // TODO 进入下一轮倒计时
                    this.refreshTime(this.code);
                    return this.fmt(content, 0, 0, 0, 0, 0, 0)
                }

                let hour = Math.floor(time / 60 / 60);
                let hour1 = Math.floor(hour / 10);
                let hour2 = Math.floor(hour % 10);

                let mn = time - hour * 60 * 60;
                let minute = Math.floor(mn / 60);
                let minute1 = Math.floor(minute / 10);
                let minute2 = Math.floor(minute % 10);

                let second = mn - minute * 60;
                let second1 = Math.floor(second / 10);
                let second2 = Math.floor(second % 10);

                return this.fmt(content, hour1, hour2, minute1, minute2, second1, second2)
            },
            set: function(){
            }
        }
    },
    mounted(){
        this.start()
    },
    methods: {
        fmt(c) {
            for (let i = 1; i < arguments.length; i++) {
                c = c.replace(new RegExp("\\{" + i + "\\}", "g"), arguments[i]);
            }
            return c;
        },
        start() {
            let self = this;
            let timer = setInterval(function() {
                self.count--;
                if(self.count <= 0){
                    clearInterval(timer);
                }
            }, 1000);
        },
        refreshTime(code) {
            let self = this;
            Box.ajax({code: code}, Route.Hall.GET_DATA, function (data) {
                new Vue({
                    el: '#_' + code,
                    data: data,
                    mounted() {
                        
                    },
                    computed: {
                        
                    }
                })
            })
        }
    }
});

2个回答

0

既然是v-bind绑定 直接更改绑定的值不就可以了么?

0

首先感谢Black_晨同学的回答,目前我采用另一种方式可以让循环继续,但是另一个问题就是继续后的值不会更新到UI上,移步:https://segmentfault.com/q/10...

撰写答案