Detailed Explanation of Vue SMS Verification Code Component Development

  • 2021-07-21 05:58:01
  • OfStack

Vue. js (pronunciation/vju/, similar to view) is a library for building data-driven web interfaces. The goal of Vue. js is to implement responsive data binding and composite view components through the simplest API possible.

Vue. js is not an all-around framework by itself--it focuses only on the view layer. Therefore, it is very easy to learn and integrate with other libraries or existing projects. On the other hand, Vue. js can also perfectly drive complex single-page applications when used with related tools and support libraries.

Summary:

1. This component is based on Vue 2.1. X version;

1. The code for the Vue component is as follows:


Vue.component('timerBtn',{
  template: '<button v-on:click="run" :disabled="disabled || time > 0">{{ text }}</button>',
  props: {
    second: {
      type: Number,
      default: 60
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data:function () {
   return {
     time: 0
   }
  },
  methods: {
    run: function () {
     this.$emit('run');
    },
    start: function(){
     this.time = this.second;
     this.timer();
    },
    stop: function(){
     this.time = 0;
     this.disabled = false;
    },
    setDisabled: function(val){
     this.disabled = val;
    },
    timer: function () {
      if (this.time > 0) {
        this.time--;
        setTimeout(this.timer, 1000);
      }else{
       this.disabled = false;
      }
    }
  },
  computed: {
    text: function () {
      return this.time > 0 ? this.time + 's  Post-retrieval ' : ' Get verification code ';
    }
  }
});

2. Usage:


<timer-btn ref="timerbtn" class="btn btn-default" v-on:run="sendCode" 
:disabled="disabled" :second="60"></timer-btn>

disabled does not recommend binding, we can call the setDisabled method of the component to switch the button available state;

second initial value 60s no special value can not be bound;

So we can do this on the HTML page:


<timer-btn ref="timerbtn" class="btn btn-default" v-on:run="sendCode" ></timer-btn>

JS looks like this:


var vm = new Vue({
  el:'#app',
  methods:{
    sendCode:function(){
      vm.$refs.timerbtn.setDisabled(true); // Settings button not available 
      hz.ajaxRequest("sys/sendCode?_"+$.now(),function(data){
        if(data.status){
          vm.$refs.timerbtn.start(); // Start countdown 
        }else{
          vm.$refs.timerbtn.stop(); // Stop the countdown 
        }
      });
    },
  }
});

Related articles: