请用vue3+scss 帮我实现倒计时组件 时分秒 时间格式hhmmss 最低为00 支持倒计时结束触发
时间: 2024-03-08 17:50:11 浏览: 58
好的!我会用Vue3和SCSS为您实现一个倒计时组件。以下是代码实现:
```vue
<template>
<div class="countdown">
<span class="countdown-item">{{ formatTime(hours) }}</span>
<span class="countdown-separator">:</span>
<span class="countdown-item">{{ formatTime(minutes) }}</span>
<span class="countdown-separator">:</span>
<span class="countdown-item">{{ formatTime(seconds) }}</span>
</div>
</template>
<script>
import { ref, computed } from "vue";
export default {
props: {
endTime: {
type: Number,
required: true,
default: Date.now() + 3600 * 1000 // 默认为1小时后
}
},
setup(props) {
const timeLeft = ref(props.endTime - Date.now());
const hours = computed(() => Math.floor(timeLeft.value / 3600000));
const minutes = computed(() => Math.floor((timeLeft.value % 3600000) / 60000));
const seconds = computed(() => Math.floor((timeLeft.value % 60000) / 1000));
const formatTime = (time) => {
return time < 10 ? `0${time}` : time.toString();
};
setInterval(() => {
timeLeft.value = props.endTime - Date.now();
}, 1000);
return {
hours,
minutes,
seconds,
formatTime
};
}
};
</script>
<style lang="scss">
.countdown {
display: flex;
justify-content: center;
align-items: center;
font-size: 24px;
}
.countdown-item {
width: 48px;
height: 48px;
display: flex;
justify-content: center;
align-items: center;
background-color: #ccc;
border-radius: 5px;
margin: 0 5px;
}
.countdown-separator {
margin: 0 5px;
}
</style>
```
使用方法:
```vue
<template>
<div>
<Countdown :endTime="endTime" @end="handleEnd" />
</div>
</template>
<script>
import Countdown from "./Countdown.vue";
export default {
components: {
Countdown
},
data() {
return {
endTime: Date.now() + 3600 * 1000 // 1小时后
};
},
methods: {
handleEnd() {
console.log("倒计时结束!");
}
}
};
</script>
```
在上面的代码中,我们使用了Vue3的Composition API来实现倒计时组件。该组件接受一个名为`endTime`的props,表示倒计时结束的时间戳。在组件的setup函数中,我们使用`ref`来创建一个名为`timeLeft`的响应式变量,用于存储倒计时剩余时间。然后,我们使用`computed`来计算出时、分、秒,并且使用`setInterval`每秒更新一次`timeLeft`的值。最后,我们使用`formatTime`方法来将数字格式化为“00”格式。如果倒计时结束,组件会触发名为`end`的事件。
阅读全文