Cam*_*ott 6 javascript vue.js vue-component vuejs2
我正在创建一个小的Timer 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>
Run Code Online (Sandbox Code Playgroud)
我切换isRunning
变量以确定计时器是否正在运行。第一次单击(播放)时,计时器开始计时并成功递增。
但是,在第二次单击(暂停)时,isRunning
变量将切换回关闭状态,但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;
},
}
})
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3786 次 |
最近记录: |