countdown timer vue
<template>
<div class="bg-white min-h-screen flex flex-col justify-center items-center">
<img src="~/assets/svg/phone-otp.svg" alt="" />
<div class="flex justify-evenly w-full my-10">
<input type="text" class="h-12 w-12 rounded-md bg-gray-300 text-lg text-center __input_next" maxlength="1" @keyup="focusNext" />
<input type="text" class="h-12 w-12 rounded-md bg-gray-300 text-lg text-center __input_next" maxlength="1" @keyup="focusNext" />
<input type="text" class="h-12 w-12 rounded-md bg-gray-300 text-lg text-center __input_next" maxlength="1" @keyup="focusNext" />
<input type="text" class="h-12 w-12 rounded-md bg-gray-300 text-lg text-center __input_next" maxlength="1" @keyup="focusNext" />
<input type="text" class="h-12 w-12 rounded-md bg-gray-300 text-lg text-center __input_next" maxlength="1" @keyup="focusNext" />
<input type="text" class="h-12 w-12 rounded-md bg-gray-300 text-lg text-center __input_next" maxlength="1" />
</div>
<div>Hantar kembali dalam</div>
<div v-if="timer !== null" class="text-primary font-bold mt-1">Waktu tersisa {{ countDownTimer }} detik</div>
<div v-else class="text-primary font-bold mt-1" @click="requestOTP">Request OTP code</div>
<div class="w-full p-5">
<div class="w-full bg-primary rounded-md text-center text-white py-2 text-lg">Sahkan</div>
</div>
<!-- otp pop up start -->
<div
class="fixed min-h-screen top-0 w-full flex justify-center items-center transition duration-500 transform"
:class="{ '-translate-y-full': !sendOtp }"
>
<div class="bg-white shadow-lg w-8/12 p-2 rounded-md flex flex-col items-center">
<div>
<i class="far fa-check-circle text-2xl text-green-500"></i>
</div>
<div>Send OTP code success !</div>
</div>
</div>
<!-- otp pop up start -->
</div>
</template>
<script>
export default {
data: () => ({
initialTimer: 60,
timer: 0,
phone: '',
audience: '',
sendOtp: false
}),
computed: {
countDownTimer() {
return this.timer
},
authAudience() {
return this.$store.state.auth.auth.audience
}
},
mounted() {
this.backTimer()
this.phone = `+${this.customerPhone || this.phone}`
this.audience = this.authAudience
},
methods: {
focusNext(event) {
event.target.nextElementSibling.focus()
},
backTimer() {
const inctTime = setInterval(() => {
const timer = this.initialTimer--
this.timer = timer
if (timer === 0) {
clearInterval(inctTime)
this.timer = null
}
}, 1000)
return inctTime
},
async requestOTP() {
try {
const res = await this.$axios.post(`${this.$config.API_URL}/auth/otp/phone`, {
phone: this.phone,
audience: this.audience
})
if (res.data) {
this.sendOtp = true
setTimeout(() => {
this.sendOtp = false
this.initialTimer = 60
this.backTimer()
}, 1500)
}
} catch (error) {
console.error(error)
}
}
}
}
</script>