123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- // components/captcha/captcha.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
- })
- },
- // 获取验证码
- getCode() {
- const { phone } = this.data;
- if (!phone || !/^1[3-9]\d{9}$/.test(phone)) {
- wx.showToast({
- title: '请输入有效的手机号码',
- icon: 'none'
- });
- return;
- }
- const generateCode = this.generateCode(); // 本地生成验证码(用于发送)
- // 保存验证码到 data
- this.setData({ generateCode });
- wx.cloud.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'
- });
- } 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
- },
- }
- })
|