Vue 5分钟倒计时组件:显示5:00并可中途停止
您可以使用Vue的计时器插件来实现一个5分钟倒计时组件,并且可以中途停止计时。以下是一个示例的组件代码:\n\nvue\n<template>\n <div>\n <span>{{ formatTime }}</span>\n <button @click="stopTimer">停止计时</button>\n </div>\n</template>\n\n<script>\n export default {\n data() {\n return {\n time: 300,\n timer: null\n };\n },\n computed: {\n formatTime() {\n const minutes = Math.floor(this.time / 60);\n const seconds = this.time % 60;\n return `${minutes}:${seconds.toString().padStart(2, '0')}`;\n }\n },\n mounted() {\n this.startTimer();\n },\n methods: {\n startTimer() {\n this.timer = setInterval(() => {\n if (this.time > 0) {\n this.time--;\n } else {\n this.stopTimer();\n }\n }, 1000);\n },\n stopTimer() {\n clearInterval(this.timer);\n }\n }\n};\n</script>\n\n\n在这个示例中,我们使用data选项来定义一个time变量,表示剩余的秒数,和一个timer变量来保存计时器的引用。我们使用computed选项来计算格式化后的倒计时时间,并在模板中显示出来。\n\n在mounted钩子函数中,我们调用startTimer方法来启动计时器。startTimer方法使用setInterval函数每秒减少time变量的值,直到time变为0或者调用stopTimer方法停止计时。在stopTimer方法中,我们使用clearInterval函数停止计时器。\n\n最后,在模板中我们使用一个按钮,当点击按钮时调用stopTimer方法来停止计时。\n\n您可以将上述代码保存到一个名为Countdown.vue的组件文件中,然后在其他地方使用<Countdown></Countdown>标签来使用这个倒计时组件。
原文地址: https://www.cveoy.top/t/topic/pKR5 著作权归作者所有。请勿转载和采集!