Vue 5分钟倒计时组件:实现计时和定格 - 代码示例
你可以使用Vue.js中的定时器和计算属性来实现5分钟倒计时组件。\n\n首先,在Vue组件中定义一个data属性来保存倒计时的剩余时间和定时器的引用:\n\njavascript\ndata() {\n return {\n remainingTime: 300,\n timer: null\n }\n}\n\n\n然后,在组件的mounted生命周期钩子中启动一个定时器,每秒减少剩余时间的值:\n\njavascript\nmounted() {\n this.timer = setInterval(() => {\n this.remainingTime -= 1;\n if (this.remainingTime <= 0) {\n clearInterval(this.timer);\n this.timer = null;\n }\n }, 1000);\n}\n\n\n接下来,定义一个计算属性来将剩余时间转换为分钟和秒钟的形式:\n\njavascript\ncomputed: {\n minutes() {\n return Math.floor(this.remainingTime / 60);\n },\n seconds() {\n return this.remainingTime % 60;\n }\n}\n\n\n最后,在组件的模板中使用计算属性来显示剩余时间:\n\nhtml\n<template>\n <div>\n <span>{{ minutes }}:{{ seconds < 10 ? '0' + seconds : seconds }}</span>\n <button @click="stopTimer">停止计时</button>\n </div>\n</template>\n\n\n在点击"停止计时"按钮时,调用一个方法来清除定时器:\n\njavascript\nmethods: {\n stopTimer() {\n clearInterval(this.timer);\n this.timer = null;\n }\n}\n\n\n这样就可以实现一个5分钟倒计时组件,当倒计时结束后,定时器会停止并且当前时间会被定格。
原文地址: https://www.cveoy.top/t/topic/pKRQ 著作权归作者所有。请勿转载和采集!