1. 程式人生 > 其它 >vue3+elementplus倒計時效果按鈕

vue3+elementplus倒計時效果按鈕

效果

在這裡插入圖片描述

程式碼實現

<template>
    <el-form label-width="80px" :model="user" :rules="ruleForgetPasswordForm">
      <el-form-item label="驗證碼" prop="verifyCode">
            <el-input v-model="user.verifyCode" placeholder="請輸入驗證碼"
minlength="4" maxlength="4">
</el-input> <el-button type="warning" :loading="checkCodeBtn.loading" :disabled="checkCodeBtn.disabled" @click="getCheckCode" style="margin-left: 5px"> {{ checkCodeBtn.text }} </
el-button
>
</el-form-item> </el-form> </template> <script lang="ts"> import {reactive, ref} from 'vue' import {ElMessage} from 'element-plus' import {isPhone, isEmail} from '@/utils/validate' export default { setup(): any { let checkCodeBtn = reactive<
any>({ text: '獲取驗證碼', loading: false, disabled: false, duration: 10, timer: null }) // 根據使用者名稱獲取驗證碼 const getCheckCode = () => { // 倒計時期間按鈕不能單擊 if (checkCodeBtn.duration !== 10) { checkCodeBtn.disabled = true } // 清除掉定時器 checkCodeBtn.timer && clearInterval(checkCodeBtn.timer) // 開啟定時器 checkCodeBtn.timer = setInterval(() => { const tmp = checkCodeBtn.duration-- checkCodeBtn.text = `${tmp}秒` if (tmp <= 0) { // 清除掉定時器 clearInterval(checkCodeBtn.timer) checkCodeBtn.duration = 10 checkCodeBtn.text = '重新獲取' // 設定按鈕可以單擊 checkCodeBtn.disabled = false } console.info(checkCodeBtn.duration) }, 1000) } return { checkCodeBtn, getCheckCode } } } }
</script>

validate.ts

// 驗證郵箱
export function isEmail(path: string): boolean {
  return /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/.test(path)
}

// 驗證手機
export function isPhone(tel: string): boolean {
  return /^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(tel)
}