跳到主要内容

发送验证码

策略类型

use hook

在使用扩展 hooks 前,确保你已熟悉了 alova 的基本使用。

验证码发送 hook,减掉你在开发验证码发送功能时的繁琐。

示例

发送验证码 Demo

特性

  • ✨ 验证码发送后自动开始倒计时;
  • ✨ 自定义倒计时秒数;
  • ✨ 验证码发送限制;

安装

# npm
npm install @alova/scene-vue --save
# yarn
yarn add @alova/scene-vue

使用

基本使用

展示表单 hook 的基本使用。

<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/scene-vue';

const mobile = ref('');
const {
// 发送状态
loading: sending,

// 调用sendCaptcha才会请求接口发送验证码
send: sendCaptcha
} = useCaptcha(() => apiSendCaptcha(mobile.value));
</script>

默认情况下,验证码发送成功后将会倒计时 60 秒,当倒计时没有结束时再调用send将会抛出错误。

自定义倒计时秒数

你也可以自定义倒计时秒数

useCaptcha(() => apiSendCaptcha(mobile.value), {
// ...
// 将倒计时设为20秒
initialCountdown: 20
});

API

Hook 配置

继承useRequestimmediate外的所有配置,useCaptchaimmediate已硬编码为 false。

名称描述类型默认值版本
initialCountdown初始倒计时,当验证码发送成功时将会以此数据来开始倒计时number60-

响应式数据

继承useRequest所有响应式数据。

名称描述类型版本
countdown当前倒计时,每秒-1,当倒计时结束后才可以再次发送验证码number-

操作函数

继承useRequest所有操作函数。

名称描述函数参数返回值版本
send发送请求,当倒计时未结束时调用将抛出错误与 useRequest.send 一致Promise<Response>-

事件

继承useRequest所有事件。