2017-04-11 98 views
5

我在每个my-progress中定义了定时器,用来更新view的值,但控制台显示的是常量变化的值,并且view的值还是没有改变,如何我可以在定时做些什么来改变的观点如何在vue组件中使用setInterval

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

回答

10

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); 
} 

How to access the correct this inside a callback?

+0

感谢您的帮助 –