Vue 获取验证码倒计时组件

子组件

<template>
    <a class="getvalidate":class="{gray: (!stop)}"@click='clickHandler'>
        {{ stop ? '获取验证码' : `(${mytimer})秒后重新获取` }}
    </a>
</template>

<script>
export default {
    name: 'getvalidate',
    data () {
        return {
            stop : true,
            mytimer: this.timer,
            Interval: null,
        }
    },
    methods: {
       clickHandler (e) {
            if (this.stop) { 
                // 调用外部绑定的倒计时,并且给它开关
                this.$emit('click', this.startTimer);
            }
       },
       update () {
           if (this.mytimer <= 1) {
              // 重置计数
              this.mytimer = this.timer
              // 清除计时器
              clearInterval(this.Interval)
              // 允许启动倒计时
              this.stop = true
           } else {
              // 倒计时
              this.mytimer--;
           }
       },
       startTimer () {
            // 开始循环执行update函数
            this.Interval = setInterval(this.update, 1000)
            // 禁止启动倒计时
            this.stop = false;
       }
    },
    props: {
       timer: {
            default: 60, 
            type: Number
       }
    }
};

</script>

<style lang="scss" scoped>
@import "./../sass/variables";
@import "./../sass/func";


.getvalidate {
    color: #0e6ae7;
    font-size: pxToRem(28px);
    width: 100%;
    text-align: right;

    &.gray {
      color: #999;
    }
}
</style>

父组件调用示例

<template>
 <div id="ForgetPwd">
       <div class="form">
            <mt-field topLabel = '请输入手机号' errTopLabel='' type = "number" placeholder = '请输入11位手机号码'  v-model = 'user'     :maxlength = '11'></mt-field>
            <mt-field topLabel = '验证码'       errTopLabel='' type = "number" placeholder = '请输入6位验证码'     v-model = 'validate' :maxlength = '6'>
                <getvalidate slot="icon" @click="getCode"></getvalidate>
            </mt-field>
            <button class="button" :class="{disable: user === '' || validate === ''}" @click="go">下一步</button>
       </div>
 </div>
</template>

<script>
import mtField from '@components/field/field.vue'
import Toast   from '@components/toast/index.js'
import Loader  from '@components/loader/index.js'
import getvalidate  from '@myComponents/getvalidate'

  export default {
        name: 'ForgetPwd',
        data () {
            return {
              user:'13713332652',
              validate: '123456'
            }
        },
        methods: {
            go () {
                
            },
            getCode (cb) {
                Loader.show("正在获取验证码")
                window.setTimeout(_ => {
                    Loader.hideAll()
                    cb()
                }, 2000)
            },
        },
        components: {
            mtField,
            getvalidate
        }
  }
</script>

 

posted @ 2018-01-31 08:22  贝尔塔猫  阅读(1848)  评论(1编辑  收藏  举报