如何在vue组件中使用setInterval [英] how to use setInterval in vue component

查看:590
本文介绍了如何在vue组件中使用setInterval的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在每个my-progress中定义了计时器,用于更新视图的值,但控制台显示常量变化的值,并且视图的值仍然没有改变,我怎么能在计时器中做到更改视图的值

I define the timer in each my-progress, used to update the value of view, but the console shows the value of the constant changes, and the value of view is still not changed, how can I do in the timer to change the value of view

Vue.component('my-progress', {
    template: '\
            <div class="progress progress-bar-vertical" data-toggle="tooltip" data-placement="top">\
                <div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" :style="{height: pgvalue}">{{pgvalue}}\
                </div>\
            </div>\
        ',
    data : function(){  

        return {
            pgvalue : '50%',
            intervalid1:'',
        }
    },
    computed:{

        changes : {
            get : function(){
                return this.pgvalue;
            },
            set : function(v){
                this.pgvalue =  v;
            }
        }
    },
    mounted : function(){

        this.todo()     
    },
    beforeDestroy () {

       clearInterval(this.intervalid1)
    },
    methods : {

        todo : function(){          
            this.intervalid1 = setInterval(function(){
                this.changes = ((Math.random() * 100).toFixed(2))+'%';
                console.log (this.changes);
            }, 3000);
        }
    },
})

这里是链接:
jsbin.com/safolom

推荐答案

未指向Vue。尝试

todo: function(){           
    this.intervalid1 = setInterval(function(){
        this.changes = ((Math.random() * 100).toFixed(2))+'%';
        console.log (this.changes);
    }.bind(this), 3000);
}

todo: function(){  
    const self = this;          
    this.intervalid1 = setInterval(function(){
        self.changes = ((Math.random() * 100).toFixed(2))+'%';
        console.log (this.changes);
    }, 3000);
}

todo: function(){  
    this.intervalid1 = setInterval(() => {
        this.changes = ((Math.random() * 100).toFixed(2))+'%';
        console.log (this.changes);
    }, 3000);
}

参见如何在回调中访问正确的

这篇关于如何在vue组件中使用setInterval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆