vue实现倒计时组件
实现基础倒计时功能
使用 Vue 的 data 和 methods 定义倒计时逻辑,通过 setInterval 更新剩余时间。
<template>
<div>{{ formattedTime }}</div>
</template>
<script>
export default {
data() {
return {
remainingTime: 60, // 初始60秒
timer: null
};
},
computed: {
formattedTime() {
const minutes = Math.floor(this.remainingTime / 60);
const seconds = this.remainingTime % 60;
return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
}
},
mounted() {
this.startTimer();
},
methods: {
startTimer() {
this.timer = setInterval(() => {
if (this.remainingTime > 0) {
this.remainingTime--;
} else {
clearInterval(this.timer);
}
}, 1000);
}
},
beforeDestroy() {
clearInterval(this.timer);
}
};
</script>
支持动态初始时间
通过 props 接收外部传入的初始时间,增强组件复用性。
<script>
export default {
props: {
initialTime: {
type: Number,
default: 60
}
},
data() {
return {
remainingTime: this.initialTime
};
}
};
</script>
添加暂停与继续功能
扩展方法控制倒计时的暂停和继续。
methods: {
pauseTimer() {
clearInterval(this.timer);
},
resumeTimer() {
this.startTimer();
}
}
自定义时间格式
通过 props 允许用户自定义时间显示格式(如 HH:MM:SS)。
props: {
format: {
type: String,
default: 'MM:SS'
}
},
computed: {
formattedTime() {
const hours = Math.floor(this.remainingTime / 3600);
const minutes = Math.floor((this.remainingTime % 3600) / 60);
const seconds = this.remainingTime % 60;
if (this.format === 'HH:MM:SS') {
return `${hours}:${minutes < 10 ? '0' : ''}${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
} else {
return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
}
}
}
事件通知
倒计时结束时触发自定义事件,便于父组件处理逻辑。
methods: {
startTimer() {
this.timer = setInterval(() => {
if (this.remainingTime > 0) {
this.remainingTime--;
} else {
clearInterval(this.timer);
this.$emit('timeup');
}
}, 1000);
}
}
使用示例
在父组件中调用倒计时组件并传递参数。
<template>
<Countdown
:initial-time="120"
format="HH:MM:SS"
@timeup="handleTimeup"
/>
</template>
<script>
import Countdown from './Countdown.vue';
export default {
components: { Countdown },
methods: {
handleTimeup() {
alert('倒计时结束!');
}
}
};
</script>






