vue 发送短信验证码倒计时

引入iview.css/vue.js/iview.js

HTML:
<div id="main" class="main">
      <i-Input class="code"  size="large">
       <timer-btn slot="append" @click.native="sendCode()" :disabled="disabled" ref="btn" :second="60"></timer-btn>
      </i-Input>
  </div>

JS:
<script type="text/javascript">
  Vue.component('timerBtn', {
  template: '<i-Button :disabled="disabled || time > 0">{{ text }}</i-Button>',
  props: {
    second: {
      type: Number,
      'default': 60 
    },
    disabled: {
      type: Boolean,
      'default': false
    }
  },
  // 初始化时间
  data: function() {
    return {
      time: 0
    };
  },
  methods: {
    run: function() {
      this.time = this.second;
      this.timer();
    },
    stop: function(){
         this.time = 0;
         this.disabled = false;
    },
    timer: function() {
      if (this.time > 0) {
        this.time--;
        setTimeout(this.timer, 1000);
      }
    }
  },
  computed: {
    text: function() {
      return this.time > 0 ? this.time + 's再获取' : '获取验证码';
    }
  }
}); 



var vm = new Vue({
    el:'#main',
    data: {
      disabled: false
    },
    methods:{
        sendCode:function(){
            vm.$refs.btn.run(); //启动倒计时
            vm.disabled = false;
        }
    }
});
 </script>

猜你喜欢

转载自www.cnblogs.com/gaomanito/p/9505816.html