实现一个小程序的验证码倒计时组件
<view class='listCode'>
<view class='list'>
<label>验证码</label>
<input type='number' bindinput="bindCode" style='width:200rpx;height:98rpx'></input>
</view>
<view class='getCode' bindtap='getCode' wx:if='{{canCode}}'>获取验证码</view>
<view class='getCode' wx:else>{{times}}后重获</view>
</view>
{
"component": true
}
通过properties接受父组件的值properties{xx:”}
通过bindCode 往父组件传值
const app = getApp()
Component({
options: {
multipleSlots: true // 在组件定义时的选项中启用多slot支持
},
properties: {
phone: { // 属性名(父组件传的值)
type: Number, // 类型(必填),目前接受的类型包括:String, Number, Boolean, Object, Array, null(表示任意类型)
value: '' // 属性初始值(可选),如果未指定则会根据类型选择一个
}
},
data: {
canCode: true,
times: 60,
name: ''
},
methods: {
// 这里放置自定义方法
getCode: function () {
var that = this;
var phone = that.data.phone;
if (phone == '') {
app.toast('请输入手机号!');
return false
}
//调取
that.settimes()
},
settimes: function () {
var that = this;
var second = that.data.times;
second--;
that.setData({
times: second,
canCode: false
})
//回调
var ss = setTimeout(function(){
that.settimes()
}, 1000);
if (second < 1) {
clearTimeout(ss);
that.setData({
canCode: true,
times:60
})
}
},
bindCode: function (e) {
var myEventDetail = {
val: e.detail.value
} // detail对象,提供给事件监听函数
this.triggerEvent('myevent', myEventDetail)
}
}
})
.listCode{
width: 638rpx;
margin: 0 auto;
overflow: hidden;
}
.list{
width: 388rpx;
height: 98rpx;
border: 1rpx solid #cccccc;
border-radius: 3px;
margin: 0 auto 40rpx;
line-height: 98rpx;
text-indent: 28rpx;
float: left;
}
.getCode{
width: 200rpx;
height: 100rpx;
line-height: 100rpx;
text-align: center;
color: #fff;
background: #13aeff;
border-radius: 3px;
float: right;
}
.list label{
color: #cecece;
width: 128rpx;
float: left;
}
使用组件
{
"navigationBarTitleText": "登陆",
"usingComponents": {
"getCode": "../component/getCode/getcode"
}
}
phone为传给子组件的值
bind:myevent是子组件中定义的函数 来获取内部的值
<getCode phone="{{phone}}" bind:myevent="onGetCode"></getCode>
onGetCode: function (e) {
this.setData({
code: e.detail.value
})
},