how to use setInterval in vue component
Solution 1:
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?
Solution 2:
check this example:
Vue.component('my-progress-bar',{
template:
`<div class="progress">
<div
class="progress-bar"
role="progressbar"
:style="'width: ' + percent+'%;'"
:aria-valuenow="percent"
aria-valuemin="0"
aria-valuemax="100">
{{ percent }}%
</div>
</div>`,
props: { percent: {default: 0} }
});
new Vue({
el: '#app',
data: {p: 50},
created: function() {
var self = this;
setInterval(function() {
if (self.p<100) {
self.p++;
}
}, 100);
}
});
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
<div id='app'>
<my-progress-bar :percent.sync='p'>
</my-progress-bar>
<hr>
<button @click='p=0' class='btn btn-danger bt-lg btn-block'>
Reset Bar Progress
</button>
</div>