我想从10倒数到0
我使用普通的javascript在线找到了解决方案,但可以说我想在Vue中实现。jQuery中的解决方案
<template>
{{ countDown }}
</template>
<script>
export default {
computed: {
countDown() {
// How do i do the simple countdown here?
}
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
如何在Vue.js中重新创建相同的功能?
谢谢
Ben*_*rey 38
虽然接受的答案工作,和是伟大的,它实际上可以在一个稍微简单的方式利用Vue.js实现观察家:
<template>
{{ timerCount }}
</template>
<script>
export default {
data() {
return {
timerCount: 30
}
},
watch: {
timerCount: {
handler(value) {
if (value > 0) {
setTimeout(() => {
this.timerCount--;
}, 1000);
}
},
immediate: true // This ensures the watcher is triggered upon creation
}
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
使用这种方法的好处是可以通过简单地设置 的值立即重置定时器timerCount。
如果您想播放/暂停计时器,那么您可以像这样实现(注意 - 这不是一个完美的解决方案,因为它会四舍五入到最近的秒):
<template>
{{ timerCount }}
</template>
<script>
export default {
data() {
return {
timerEnabled: true,
timerCount: 30
}
},
watch: {
timerEnabled(value) {
if (value) {
setTimeout(() => {
this.timerCount--;
}, 1000);
}
},
timerCount: {
handler(value) {
if (value > 0 && this.timerEnabled) {
setTimeout(() => {
this.timerCount--;
}, 1000);
}
},
immediate: true // This ensures the watcher is triggered upon creation
}
}
methods: {
play() {
this.timerEnabled = true;
},
pause() {
this.timerEnabled = false;
}
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
请检查是否适合您。
<template>
{{ countDown }}
</template>
<script>
export default {
data() {
return {
countDown : 10
}
},
method: {
countDownTimer() {
if(this.countDown > 0) {
setTimeout(() => {
this.countDown -= 1
this.countDownTimer()
}, 1000)
}
}
}
created: {
this.countDownTimer()
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
Here is a component I made for a countdown timer :
<template>
<div>
<slot :hour="hour" :min="min" :sec="sec"></slot>
</div>
</template>
<script>
export default {
props : {
endDate : { // pass date object till when you want to run the timer
type : Date,
default(){
return new Date()
}
},
negative : { // optional, should countdown after 0 to negative
type : Boolean,
default : false
}
},
data(){
return{
now : new Date(),
timer : null
}
},
computed:{
hour(){
let h = Math.trunc((this.endDate - this.now) / 1000 / 3600);
return h>9?h:'0'+h;
},
min(){
let m = Math.trunc((this.endDate - this.now) / 1000 / 60) % 60;
return m>9?m:'0'+m;
},
sec(){
let s = Math.trunc((this.endDate - this.now)/1000) % 60
return s>9?s:'0'+s;
}
},
watch : {
endDate : {
immediate : true,
handler(newVal){
if(this.timer){
clearInterval(this.timer)
}
this.timer = setInterval(()=>{
this.now = new Date()
if(this.negative)
return
if(this.now > newVal){
this.now = newVal
this.$emit('endTime')
clearInterval(this.timer)
}
}, 1000)
}
}
},
beforeDestroy(){
clearInterval(this.timer)
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2132 次 |
| 最近记录: |