首先,我们先认识一下自定义组件的一些基本知识,要知道它和page一样,都包含4个文件(wxml、wxss、js、json)。
1、先在自定义组件的json文件里设置:
{ "component": true }
自定义组件的模板:
1 Component({ 2 options: { 3 multipleSlots: true // 在组件定义时的选项中启用多slot支持 4 }, 5 properties: { 6 // 传入组件的数据 7 innerText: { 8 type: String, 9 value: 'default value', 10 } 11 }, 12 data: { 13 // 这里是一些组件内部数据 14 }, 15 methods: { 16 // 这里是一个自定义方法 17 } 18 })
2、在要引用该组件的页面的json中配置:
{ "usingComponents": { "component-tag-name": "path/to/the/custom/component" } }
在页面引用,标签名只能是小写字母、中划线和下划线的组合
<component-tag-name inner-text="Some text"></component-tag-name>
那么接下来开始实践一下。因为平时的一些应用中,发送验证码,是比较常见的功能,所以我们可以把这个单独做成一个组件,以便之后的复用。
思路:单独把发送验证码作为一个组件,传入手机号,在组件内判断是否为合法的手机号,如果是,则调用接口获取验证码,按钮置灰,显示60s倒计时。超过60s即可重新获取验证码。代码如下:
1 const app = getApp() 2 Component({ 3 /** 4 * 组件的属性列表 5 */ 6 properties: { 7 phone:{//请求的电话号码 8 type:Number, 9 value:'' 10 }, 11 checkPhone:{//是否验证手机号是否存在(适合忘记密码时使用) 12 type:Boolean, 13 value:'' 14 } 15 }, 16 17 /** 18 * 组件的初始数据 19 */ 20 data: { 21 codemsg:'', 22 btntxt: '获取验证码', 23 time:60, 24 InterValObj:'', //计时器 25 isSend:false 26 }, 27 28 /** 29 * 组件的方法列表 30 */ 31 methods: { 32 SetRemainTime: function () { 33 let time = this.data.time 34 if (this.data.time == 0) { 35 clearInterval(this.data.InterValObj); //停止计时器 36 this.setData({ 37 isSend:false, 38 time:60, 39 btntxt:'重新发送验证码' 40 }) 41 } 42 else { 43 time-- 44 this.setData({ 45 time:time, 46 isSend:true, 47 btntxt:time+'s' 48 }) 49 } 50 }, 51 getCode(){ 52 let reg = /^1[345678]\d{9}$/; 53 let phone = this.properties.phone 54 if (!(reg.test(phone))) { 55 this.triggerEvent('transCode', { error: true}) 56 return false; 57 } 58 if (this.properties.checkPhone){ 59 //接口请求是我自己又封装的小程序request API,没什么技术难度,就不献上了 60 app.ajax('get', 'api/validate/check_mobile_exist', { mobile: this.data.phone }, (res) => { 61 if (res.data.code == '0') { 62 this.triggerEvent('transCode', { hasPhone: true }) 63 return false 64 } 65 this.sendCode() 66 }, (error) => { 67 }) 68 69 } 70 if (!this.properties.checkPhone){ 71 this.sendCode() 72 } 73 }, 74 sendCode(){ 75 let phone = this.properties.phone 76 app.ajax('get', 'api/user/sendmsg', { phone: phone }, (res) => { 77 if (res.data.code == '0') { 78 return wx.showToast({ 79 title: '你操作过于频繁,请稍后再试', 80 icon:'none', 81 duration:2000 82 }) 83 } 84 let code = res.data.data.msg 85 this.triggerEvent('transCode', { code: code }) 86 this.setData({ 87 InterValObj: setInterval(() => { this.SetRemainTime() }, 1000) 88 }) 89 }, (error) => { 90 91 }) 92 } 93 } 94 })
假设在注册页面引入,或者忘记密码页面使用:
<get-code phone="{{phone}}" bind:transCode="getCode" checkPhone="{{true}}"></get-code>