Component({ properties: { isShow: { type: Boolean, value: false }, type: { type: String, value: 'code' // 'code' 验证码 / '结算' 结算密码 }, // 新增:外部可配置倒计时总时长(默认60秒) countdownTotal: { type: Number, value: 60 } }, data: { codes: [], // 输入框显示的数组 currentIndex: 0, // 当前激活索引 isFocus: false, // 输入框聚焦状态 codeValue: '', // 4位验证码真实值 oncodeValue: '', // 6位结算密码真实值 isShakeError: false, // 晃动动画开关 // 新增:倒计时相关数据 countdown: 0, // 当前剩余倒计时秒数 timer: null // 倒计时定时器(用于清除定时器,防止内存泄漏) }, // 新增:组件卸载时清除定时器,防止内存泄漏 detached() { clearInterval(this.data.timer); }, methods: { // 关闭弹窗 onClose() { this.triggerEvent('close'); this.resetInput(); // 关闭时重置输入 this.resetCountdown(); // 关闭时重置倒计时 }, // 聚焦输入框 focusInput() { this.setData({ isFocus: true }); }, // 输入内容处理 onCodeInput(e) { console.log(e); const value = e.detail.value; const len = this.data.type === '结算' ? 6 : 4; const codes = value.split('').slice(0, len); this.setData({ codes: codes, currentIndex: codes.length, codeValue: this.data.type !== '结算' ? value : this.data.codeValue, oncodeValue: this.data.type === '结算' ? value : this.data.oncodeValue }); // 输入完成:仅传递值给父组件,不做检验 if (codes.length === len) { const finalValue = this.data.type === '结算' ? this.data.oncodeValue : this.data.codeValue; // 向父组件发送输入完成的事件,携带输入值 this.triggerEvent('inputComplete', { value: finalValue }); this.setData({ isFocus: false }); } }, // 输入框失焦 onInputBlur() { this.setData({ isFocus: false }); }, // 重新发送验证码(仅传递事件给父组件,并启动倒计时) onResend() { // 启动倒计时(防止重复点击重复启动定时器) this.startCountdown(); // 向父组件发送重新发送事件 this.triggerEvent('resend'); }, // 重置输入内容(供父组件/自身调用) resetInput() { this.setData({ codes: [], currentIndex: 0, codeValue: '', oncodeValue: '' }); }, // 触发失败动效(供父组件调用) triggerErrorShake() { this.setData({ isShakeError: true }); // 动画结束后重置状态 setTimeout(() => { this.setData({ isShakeError: false }); }, 500); // 同时清空输入 this.resetInput(); }, // 新增:启动倒计时 startCountdown() { // 1. 先清除已有定时器,防止重复创建 clearInterval(this.data.timer); // 2. 初始化倒计时为总时长 const total = this.data.countdownTotal; this.setData({ countdown: total }); // 3. 创建定时器,每秒更新倒计时 const timer = setInterval(() => { this.setData({ countdown: this.data.countdown - 1 }, () => { // 4. 倒计时结束后清除定时器,重置倒计时状态 if (this.data.countdown <= 0) { clearInterval(this.data.timer); this.resetCountdown(); } }); }, 1000); // 5. 保存定时器实例,用于后续清除 this.setData({ timer }); }, // 新增:重置倒计时(恢复初始状态) resetCountdown() { clearInterval(this.data.timer); this.setData({ countdown: 0, timer: null }); } } });