// components/captcha/captcha.js import { getDB, getModels, getCommand, getTempFileURLs, getClient } from '../../utils/cloudbase.js' Component({ /** * 组件的属性列表 */ properties: { phone: { type: String, required: true }, }, /** * 组件的初始数据 */ data: { generateCode: '-999999', // 点击发送验证码时生成的验证码 userCode: '', // 用户输入的验证码 defaultCode: '989898', // 测试时使用 }, /** * 组件的方法列表 */ methods: { /** * 监听验证码输入 * @param {*} e */ onInputCode(e) { this.setData({ userCode: e.detail.value }) }, // 获取验证码 async getCode() { const { phone } = this.data; if (!phone || !/^1[3-9]\d{9}$/.test(phone)) { wx.showToast({ title: '请输入有效的手机号码', icon: 'none' }); return; } const generateCode = this.generateCode(); // 本地生成验证码(用于发送) this.setData({ generateCode, isSending: true }); wx.showLoading({ title: '获取中...', mask: true }); // 保存验证码到 data const client = await getClient(); this.setData({ generateCode }); client.callFunction({ // 云函数名称 name: 'lxp', // 传给云函数的参数 data: { mobile: this.data.phone, code: generateCode, }, }).then(res => { if (res.result.response.code === 200) { console.log('数据获取成功 =>', res.result.response); wx.showToast({ title: '验证码发送成功', icon: 'none' }); // 启动倒计时 this.startCountdown(60); } else { console.error('数据获取失败 =>', res.result.response); wx.showToast({ title: '验证码发送失败', icon: 'none' }); } }).catch(error => { console.error(error) wx.showToast({ title: '验证码发送失败', icon: 'none' }); }) }, /** * 生成验证码 */ generateCode() { return Math.floor(100000 + Math.random() * 900000).toString(); }, /** * 校验验证码 */ validCaptcha() { const { generateCode, userCode, defaultCode } = this.data const flag = generateCode === userCode || defaultCode === userCode const result = { flag, msg: '', } if (!flag) { result.msg = '验证码输入错误' } if (!userCode) { result.msg = '请输入验证码' } return result }, startCountdown(seconds) { this.setData({ countdown: seconds }); const timer = setInterval(() => { if (this.data.countdown <= 1) { clearInterval(timer); this.setData({ countdown: 0, isSending: false }); // 倒计时结束后重置 isSending } else { this.setData({ countdown: this.data.countdown - 1 }); } }, 1000); }, } })