vue之开发一个验证码倒计时组件

说明

前端开发在做登录功能时,倒计时获取验证码的情况很是普遍

实现效果

父组件代码 [ Login.vue ]
<template>
  <div class="regandlogin">
    <div class="regandlogin-tip"><i class="icon icon-info"></i>为确保企业资金安全,请确认手机号。</div>
    <form >
      <p class="input-wrapper" style="border-top: 1px solid #ddd;">
      <span class="label">手机号</span>
      <input type="text" maxlength="11"  v-model="userInfo.phoneNum" placeholder="请输入企业负责人手机号">
      </p>
           
      <p  class="input-wrapper">
      <span class="label">验证码</span>
      <input maxlength="6" type="number" placeholder="6位短信验证码" v-model="userInfo.validCode">
      <count-down class="sm-btn"  :fn="getValidCode" :deftext="'获取'" ref='btn'  :second='60'></count-down>
      </p>

      <p class="sub-ops mg-t-10 pd-l-r-10">
      <a class="btn-block btnred" href="javascript:;" @click="goLogin()">确认</a>
      </p>
    </form>
    </div>
</template>

<script>

import CountDown from 'components/CountDown'

export default {
  name: 'Login',
  data () {
    return {
      userInfo:{
        phoneNum:'15611192643',
        validCode:''
      },
      sending:false
    }
  },
  methods:{
    getValidCode:function(){
      if(this.sending){
        return;
      }
      console.log('发送验证码');
      var _self=this;
      this.$http.post('http://www.xxx.com/send_captchar',{
                mobile:this.userInfo.phoneNum
            },{
                emulateJSON:true
            }).then(function(res){

                //开始倒计时
                _self.$refs.btn.run();
                //禁用重新发送按钮
                _self.sending=true;
                setTimeout(this.sended, 60000);
                console.log(res.data);
            },function(res){
                alert(res.status);
            });
    },
    goLogin:function(){
      console.log('登录');
      console.log(this.userInfo);
    },
    sended:function(){
      this.sending=false;
    }
  },
  components:{
    'CountDown':CountDown
  }

}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
CountDown组件代码
<template>
  <span @click='fn'>
  {{btn_text}}
  </span>
</template>

<script>
export default {
  name: 'countDown',
  data () {
    return {
      time:0
    }
  },
  props:['deftext','second','fn'],
  methods:{
    run: function () {
        this.time = this.second
        this.timer()
    },
    timer:function(event){
        if (this.time > 0) {
            this.time--;
            setTimeout(this.timer, 1000);
        }
    }
  },
  computed:{
    btn_text:function() {
      return this.time > 0 ? this.time + 's' : this.deftext;
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 关于读诗这事就跟爱情是一样的。 那首诗、那个诗人,你一读就懂了,那就是懂了。可以懂得热泪盈眶、直击灵魂。可若不懂,...
    悦心堂悦心阅读 219评论 0 0
  • 1 晚上窝在宿舍扎堆刷微博的时候,禾子突然嚎啕大哭起来。 我被吓了一跳,不过看到她手机屏幕的时候,瞬间明白了怎么回...
    曹痞阅读 2,300评论 38 58