发送验证码
策略类型
use hook
在使用扩展 hooks 前,确保你已熟悉了 alova 的基本使用。
验证码发送 hook,减掉你在开发验证码发送功能时的繁琐。
特性
- 验证码发送后自动开始倒计时;
- 自定义倒计时秒数;
- 验证码发送限制;
使用
基本使用
展示表单 hook 的基本使用。
- vue
- react
- svelte
<template>
<input v-model="mobile" />
<button
@click="sendCaptcha"
:loading="sending"
:disabled="sending || countdown > 0">
{{ loading ? '发送中...' : countdown > 0 ? `${countdown}后可重发` : '发送验证码' }}
</button>
</template>
<script setup>
import { ref } from 'vue';
import { apiSendCaptcha } from './api.js';
import { useCaptcha } from 'alova/client';
const mobile = ref('');
const {
// 发送状态
loading: sending,
// 调用sendCaptcha才会请求接口发送验证码
send: sendCaptcha
} = useCaptcha(() => apiSendCaptcha(mobile.value));
</script>
import { useState } from 'react';
import { apiSendCaptcha } from './api.js';
import { useCaptcha } from 'alova/clientct';
const App = () => {
const [mobile, setMobile] = ref('');
const {
// 发送状态
loading: sending,
// 调用sendCaptcha才会请求接口发送验证码
send: sendCaptcha
} = useCaptcha(() => apiSendCaptcha(mobile));
return (
<div>
<input
value={mobile}
onChange={({ target }) => setMobile(target.value)}
/>
<button
onClick={sendCaptcha}
loading={sending}
disabled={sending || countdown > 0}>
{loading ? '发送中...' : countdown > 0 ? `${countdown}后可重发` : '发送验证码'}
</button>
</div>
);
};
<script>
import { apiSendCaptcha } from './api.js';
import { useCaptcha } from 'alova/client';
let mobile = '';
const {
// 发送状态
loading: sending,
// 调用sendCaptcha才会请求接口发送验证码
send: sendCaptcha
} = useCaptcha(() => apiSendCaptcha(mobile));
</script>
<input bind:value="{mobile}" />
<button
on:click="{sendCaptcha}"
loading="{$sending}"
disabled="{$sending || $countdown > 0}">
{ $loading ? '发送中...' : $countdown > 0 ? `${$countdown}后可重发` : '发送验证码' }
</button>
默认情况下,验证码发送成功后将会倒计时 60 秒,当倒计时没有结束时再调用send
将会抛出错误。
自定义倒计时秒数
你也可以自定义倒计时秒数
useCaptcha(() => apiSendCaptcha(mobile.value), {
// ...
// 将倒计时设为20秒
initialCountdown: 20
});