How to use setInterval in vue component

I define a timer in each of my progress, which is used to update the value of the view, but the console displays the value of constant changes, and the view value still does not change, how can I do in the timer change the value of the 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); } }, }) 

here is the link: jsbin.com/safolom

+7
vuejs2 vue-component
source share
1 answer

this does not point to 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?

+11
source share

All Articles