小程序-手机验证码倒计时

用的有赞组件

<van-cell-group> 
  <van-field
    value="{{ phone }}"
    label="手机号"
    placeholder="请输入手机号" 
    border="{{ false }}"
    bind:change="change"
  />
   <van-field
    value="{{ sms }}"
    center
    clearable
    label="短信验证码"
    placeholder="请输入短信验证码"
    border="{{ false }}"
    use-button-slot
    bind:change="change_code"
  >
    <van-button slot="button" wx:if="{{send_state}}" size="small" type="primary" bindtap='send'>发送验证码</van-button>
    <van-button slot="button" wx:else disabled size="small" type="default">{{miao}}秒</van-button>
    
  </van-field>
</van-cell-group>
<view class="c_t">
<van-button slot="button" size="small" type="danger" bindtap='sub'>绑定</van-button>
</view>
//我这里是封装的http,可直接用wx.request代替
import { HTTP } from '../../util/http.js';
const http = new HTTP

Page({

  data: {
    phone: "",
    code: "",
    send_state: true,
    smiao: 10
  },
  change(event) {
    const phone = event.detail;
    this.setData({
      phone
    })
  },
  change_code(event) {
    const code = event.detail;
    this.setData({
      code
    })
  },
  sub() {
    const phone = this.data.phone
    const code = this.data.code
    if(this.checkPhone(phone)<1){
      return;
    }
    if (code.length<4){
      wx.showToast({
        title: '验证码有误',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    http.request({
      url:'',
      method:'post',
      data:{
        phone,
        code
      }
    })
  },
  send() {
    const that = this
    const phone = this.data.phone
    const check = this.checkPhone(phone)
    const smiao = that.data.smiao
    if (check == 1) {
      this.setData({
        send_state: false,
        miao: smiao
      })
      this.settime(smiao)
    }
  },
  checkPhone(phone) {
    if (!(/^1[34578]\d{9}$/.test(phone))) {
      wx.showToast({
        title: '手机号有误',
        icon: 'none',
        duration: 2000
      })
      return 0;
    } else {
      return 1;
    }
  },
  settime(miao) {
    const that = this
    const smiao = that.data.smiao
    if (miao == 0) {
      console.log('stop')
      that.setData({
        miao: smiao,
        send_state: true
      })
    } else {
      setTimeout(() => {
        miao--
        that.setData({
          miao
        })
        that.settime(miao)
      }, 1000)
    }

  }
})
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 从小程序基础库版本 1.6.3 开始,小程序支持简洁的组件化编程。查看自己使用的小程序基础库版本,可以通过在开发者...
    极乐叔阅读 1,609评论 0 9
  • 1.小程序起步 (1)点击https://mp.weixin.qq.com/wxopen/waregister?a...
    GXW_Lyon阅读 3,480评论 0 0
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,301评论 4 61
  • 今天有一条感悟:不要和同事做朋友。 首先第一条原因是,成为朋友之后,关系太好了,没有办法告诉他,这是公司规则,我没...
    蓝小撞阅读 1,846评论 0 0
  • 夜幕降临时 就已经看不清你的样子 像隐在烟雾水幕后的影子 抓不住 触不及 还来不及思考生活难题 憧憬在前路美好梦幻...
    飞天骑小马扎阅读 222评论 0 0