Component({ properties: { // 是否显示弹窗 isShow: { type: Boolean, value: false }, // 手机号(用于显示) phoneNumber: { type: String, value: '' }, // 倒计时秒数 countdownSeconds: { type: Number, value: 60 } }, data: { // 验证码数组(6位) codes: ['', '', '', '', '', ''], // 实际输入的验证码值 codeValue: '', // 当前激活的输入框索引 currentIndex: 0, // 是否聚焦 isFocus: false, // 倒计时 countdown: 60, // 是否可以重新发送 canResend: false, // 验证码是否输入完成 isComplete: false, // 倒计时计时器 timer: null }, observers: { // 监听isShow变化,控制弹窗显示隐藏 isShow: function (isShow) { if (isShow) { this.startCountdown(); this.focusInput(); } else { this.clearCountdown(); this.resetCodeInput(); } }, // 监听countdownSeconds变化 countdownSeconds: function (seconds) { this.setData({ countdown: seconds }); }, // 监听验证码变化,更新输入状态 codeValue: function (value) { const codes = []; for (let i = 0; i < 6; i++) { codes[i] = value[i] || ''; } // 更新当前激活的输入框索引 let currentIndex = value.length < 6 ? value.length : 5; // 判断是否输入完成 const isComplete = value.length === 6; this.setData({ codes, currentIndex, isComplete }); // 如果输入完成,自动触发确认事件 if (isComplete) { this.triggerEvent('complete', { code: value }); } } }, methods: { // 聚焦输入框 focusInput() { this.setData({ isFocus: true }); }, // 输入框失焦 onInputBlur() { this.setData({ isFocus: false }); }, // 验证码输入 onCodeInput(e) { const value = e.detail.value.replace(/\D/g, ''); // 只保留数字 this.setData({ codeValue: value }); }, // 关闭弹窗 onClose() { this.triggerEvent('close'); }, // 确认 onConfirm() { if (this.data.isComplete) { this.triggerEvent('confirm', { code: this.data.codeValue }); } }, // 重新发送验证码 onResend() { this.triggerEvent('resend'); this.startCountdown(); }, // 开始倒计时 startCountdown() { // 清除之前的计时器 this.clearCountdown(); const countdownSeconds = this.data.countdownSeconds; this.setData({ countdown: countdownSeconds, canResend: false }); // 设置新的计时器 const timer = setInterval(() => { let countdown = this.data.countdown - 1; if (countdown <= 0) { this.setData({ countdown: 0, canResend: true }); this.clearCountdown(); } else { this.setData({ countdown }); } }, 1000); this.setData({ timer }); }, // 清除倒计时 clearCountdown() { if (this.data.timer) { clearInterval(this.data.timer); this.setData({ timer: null }); } }, // 重置验证码输入 resetCodeInput() { this.setData({ codes: ['', '', '', '', '', ''], codeValue: '', currentIndex: 0, isComplete: false }); } }, // 组件销毁时清除计时器 detached() { this.clearCountdown(); } });