programing

vue 구성 요소에서 setInterval을 사용하는 방법

prostudy 2022. 5. 31. 07:46
반응형

vue 구성 요소에서 setInterval을 사용하는 방법

각 my-progress에서 타이머를 정의하며 뷰 값을 갱신하는데 사용되지만 콘솔에 계속 변경 값이 표시되며 뷰 값은 변경되지 않습니다. 타이머에서 뷰 값을 변경하려면 어떻게 해야 합니까?

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

thisVue를 가리키고 있지 않습니다.해라

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

자세한 내용은 콜백 내에서 올바른액세스하는 방법을 참조하십시오.

다음 예를 확인합니다.

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>

언급URL : https://stackoverflow.com/questions/43335477/how-to-use-setinterval-in-vue-component

반응형