how to use setInterval in vue component

前端 未结 2 752
有刺的猬
有刺的猬 2020-12-14 00:04

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

2条回答
  •  隐瞒了意图╮
    2020-12-14 00:38

    this is not pointing to the Vue. Try

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

    or

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

    or

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

    See How to access the correct this inside a callback?

提交回复
热议问题