如何在Vue组件中使用setInterval

67

我在我的进度条中定义了一个计时器,用于更新视图的值,但控制台显示常数的值发生了变化,而视图的值仍然没有改变,我应该如何在计时器中改变视图的值。

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

3个回答

90

this并不指向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);
}

请参考如何在回调函数中访问正确的this


1
为了澄清,第一个示例使用 function(){}.bind() 来重新分配 this,第二个示例使用本地的 self 变量分配到正确的 this,第三个示例使用 lambda () => {} 语法,它会自动绑定 this。我认为第三个选项是首选。 - Nathan Goings

7

看这个例子:

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>


0

created : {

  window.setInterval(() => {
    getList(); // call any function or end point
  }, 1000); // interval set to one sec. 

}


const getList = () => {
    console.log('foo')
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接