Home > Article > Web Front-end > How to implement countdown and alarm clock functions in uniapp
How to implement countdown and alarm clock functions in uniapp
1. Implementation of countdown function:
The countdown function is very common in actual development and can Used to implement various countdown functions, such as verification code countdown, flash sale countdown, etc. The following uses the uniapp framework to introduce how to implement the countdown function.
<template> <div>{{ countDown }}</div> </template> <script> export default { data() { return { countDown: 60, // 倒计时时长 timer: null // 计时器对象 } }, mounted() { this.startCountdown() }, methods: { startCountdown() { this.timer = setInterval(() => { if (this.countDown > 0) { this.countDown-- } else { clearInterval(this.timer) this.timer = null } }, 1000) }, stopCountdown() { clearInterval(this.timer) this.timer = null } } } </script>
<template> <div> <countdown></countdown> <button @click="stopCountdown">停止倒计时</button> </div> </template> <script> import Countdown from '@/components/Countdown.vue' export default { components: { Countdown }, methods: { stopCountdown() { this.$refs.countdown.stopCountdown() } } } </script>
Through the above code, introduce the Countdown component into the page and use it to start the timer in the mounted hook function.
2. Implementation of the alarm clock function:
The alarm clock function is also very common in actual development, and can realize functions such as regular reminders. The following uses the uniapp framework to introduce how to implement the alarm clock function.
<template> <div>{{ currentTime }}</div> </template> <script> export default { data() { return { currentTime: '', // 当前时间 timer: null // 计时器对象 } }, mounted() { this.startAlarmClock() }, methods: { startAlarmClock() { this.timer = setInterval(() => { const now = new Date(); const hours = now.getHours(); const minutes = now.getMinutes(); const seconds = now.getSeconds(); this.currentTime = `${hours}:${minutes}:${seconds}`; }, 1000) }, stopAlarmClock() { clearInterval(this.timer) this.timer = null } } } </script>
<template> <div> <alarm-clock></alarm-clock> <button @click="stopAlarmClock">停止闹钟</button> </div> </template> <script> import AlarmClock from '@/components/AlarmClock.vue' export default { components: { AlarmClock }, methods: { stopAlarmClock() { this.$refs.alarmClock.stopAlarmClock() } } } </script>
Through the above code, introduce the AlarmClock component into the page and use it to start the timer in the mounted hook function.
The above is how to implement countdown and alarm clock functions in uniapp. I hope it will be helpful to you. At the same time, this is just a basic sample code that you can modify and optimize according to actual needs.
The above is the detailed content of How to implement countdown and alarm clock functions in uniapp. For more information, please follow other related articles on the PHP Chinese website!