vue组件中setInterval的使用方法

新手上路,请多包涵

我在每个my-progress中都定义了timer,用来更新view的值,但是console显示的值一直在变化,而view的值还是没有变化,请问怎么才能在timer中改变这个值观点

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

原文由 A_Wen 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 343
2 个回答

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

原文由 Bert 发布,翻译遵循 CC BY-SA 3.0 许可协议

检查这个例子:

 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>

原文由 fitorec 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题