반응형
Vue를 사용하여 초 단위로 카운트업
작은 타이머 Vue 컴포넌트를 만들고 있습니다.사용자는 그 타이머를 기동 및 정지할 수 있어야 합니다.지금까지의 컴포넌트는 다음과 같습니다.
<template>
<div>
<a class="u-link-white" href="#" @click="toggleTimer">
{{ time }}
</a>
</div>
</template>
<script>
export default {
props: ['order'],
data() {
return {
time: this.order.time_to_complete,
isRunning: false,
}
},
methods: {
toggleTimer() {
var interval = setInterval(this.incrementTime, 1000);
if (this.isRunning) {
//debugger
clearInterval(interval);
console.log('timer stops');
} else {
console.log('timer starts');
}
this.isRunning = (this.isRunning ? false : true);
},
incrementTime() {
this.time = parseInt(this.time) + 1;
},
}
}
</script>
토글하고 있습니다.isRunning
variable을 지정하여 타이머가 실행 중인지 여부를 판별합니다.첫 번째 클릭 시(재생) 타이머가 시작되고 정상적으로 증가합니다.
단, 두 번째 클릭(일시정지)에서는isRunning
var는 다시 꺼짐으로 전환되지만clearInterval(this.incrementTime)
는 인터벌을 클리어하지 않고 타이머를 일시 정지하지 않습니다.그 디버거를 삽입하고 수동으로 이 디버거가clearInterval(interval)
콘솔을 통해 정의되지 않은 상태로 반환됩니다.
컴포넌트를 올바르게 포맷하지 않은 방법을 알고 있는 사람이 있습니까?
위의 코멘트에서 설명한 개념에 대한 작업 예를 다음에 제시하겠습니다.이것은 컴포넌트의 정확한 실장은 아닙니다.그냥 컴포넌트가 어떻게 동작하는지를 보여주는 예에 불과합니다.
console.clear()
new Vue({
el: "div",
data() {
return {
time: 0,
isRunning: false,
interval: null
}
},
methods: {
toggleTimer() {
if (this.isRunning) {
clearInterval(this.interval);
console.log('timer stops');
} else {
this.interval = setInterval(this.incrementTime, 1000);
}
this.isRunning = !this.isRunning
},
incrementTime() {
this.time = parseInt(this.time) + 1;
},
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
<div>
<a class="u-link-white" href="#" @click="toggleTimer">
{{ time }}
</a>
</div>
<template>
<div>
<a class="u-link-white" href="#" @click="toggleTimer">
{{ time }}
</a>
</div>
</template>
<script>
export default {
props: ['order'],
data() {
return {
time: this.order.time_to_complete,
isRunning: false,
interval: undefined // store the interval here
}
},
methods: {
toggleTimer() {
if (this.isRunning) {
clearInterval(this.interval);
console.log('timer stops');
} else {
this.interval = setInterval(this.incrementTime, 1000);
console.log('timer starts');
}
this.isRunning = !this.isRunning; // better to read
},
incrementTime() {
this.time = parseInt(this.time) + 1;
},
}
}
</script>
추가 테스트를 거치지 않고는 첫 번째 인터벌로의 포인터가 기능 범위 내에 있기 때문에 절대 멈추지 않는다고 생각합니다.따라서 메서드가 두 번째로 호출되었을 때 사용할 수 있기 때문에 데이터 오브젝트에 인터벌을 삭제했습니다.도움이 되었으면 좋겠다
언급URL : https://stackoverflow.com/questions/47944557/using-vue-to-count-up-by-seconds
반응형
'programing' 카테고리의 다른 글
vue2: 컴포넌트에 여러 개의 소품을 전달할 수 있습니까? (0) | 2022.07.21 |
---|---|
어레이 길이 속성은 어디에 정의됩니까? (0) | 2022.07.21 |
asm, _asm, _asm_의 차이점은 무엇입니까? (0) | 2022.07.21 |
Haskell에서 이 수치 계산의 성능을 향상시키는 방법은 무엇입니까? (0) | 2022.07.18 |
Vue.js 2.0 - vue 반응성의 혼란 (0) | 2022.07.18 |