// components/send-code/send-code.js let setInter = null; import { imgServerUrl } from '../../config/config.js' Component({ /** * 组件的属性列表 */ properties: { // 需要发送验证码的电话号码 phone: { type: String, value: ' ', observer(data) { if (data) { const _data = data.toString(); const format_phone = _data.substring(0, 3) + ' ' + _data.substring(3, 7) + ' ' + _data.substring(7, 11); this.setData({ format_phone }) } } }, // 需要跳转的地址 暂未使用 url: { type: String, value: '' }, // 自动清除已输入文字 reset: { type: String, observer() { this.setData({ code: [] }) } }, // 自动发送 主要用于绑定手机号码时 auto_send: { type: Boolean, value: false, observer(data) { if (data === true) { this.send() } } } }, /** * 组件的初始数据 */ data: { img: imgServerUrl + '/images/happyjob/login_xiaobai.png', hidden: true, //键盘是否抬起 默认是 step: 1000, // 倒计时的步长 countdown: '点击发送验证码', //点击的按钮文字 code: [], // 验证码 numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0], // 键盘原始数组 keybord: [], //键盘实际渲染数组 time: 60, // 倒计时时长 format_phone: '' //整理格式后的电话号码 }, ready() { // 初始化界面 this.init(); }, detached() { clearInterval(setInter) }, /** * 组件的方法列表 */ methods: { // 初始化方法 生成键盘布局数组 init(status) { // 原始数组 const arr = this.data.numbers; // 实际渲染数组 let keybord = []; // 如果status = true 则打乱排序生成新的原始数组 if (status) { for (let i = 0, len = arr.length * 2; i < len; i++) { var rdm = Math.floor(Math.random() * arr.length) arr.push(arr[rdm]) arr.splice(rdm, 1) } } // 将原始数组切割成四个小数组 方便渲染 for (let i = 0; i < 4; i++) { keybord.push(arr.slice(i * 3, (i + 1) * 3)) } this.setData({ keybord, hidden: false }) }, // 键盘事件 点击之后 keyboard(e) { const { value } = e.currentTarget.dataset; const code = this.data.code; // push 进入验证码数组 if (code.length < 6) { code.push(value); this.setData({ code }) // 当数组长度达到的时候 触发完成方法 if (code.length === 6) { this.triggerEvent('done', { code: this.data.code.join('') }) } } }, // 删除验证码 del() { const code = this.data.code; code.pop(); this.setData({ code }) }, // 发送验证码 send() { const time = this.data.time; if (time === 60) { this.countdown(); this.setData({ hidden: false }) this.triggerEvent('send') } }, // 取消按键 点击键盘收起 cancel() { this.setData({ hidden: true }) }, // 键盘唤醒时 添加标签闪烁效果 showFlash(e) { this.setData({ hidden: false }) }, // 倒计时 countdown() { let _time = this.data.time; _time--; this.setData({ time: _time, countdown: `${_time}s后重新发送` }) setInter = setInterval(() => { let _time = this.data.time; if (_time > 1) { _time--; this.setData({ time: _time, countdown: `${_time}s后重新发送` }) } else { clearInterval(setInter); this.setData({ time: 60, countdown: `重新发送验证码` }, _ => { setInter = null; }) } }, this.data.step) } } })