温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Vue 中怎么实现一个短信验证码组件

发布时间:2021-07-09 11:21:36 来源:亿速云 阅读:197 作者:Leah 栏目:web开发

本篇文章给大家分享的是有关Vue 中怎么实现一个短信验证码组件,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

1、 Vue 组件代码如下:

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 后重获取' : '获取验证码';
    }
  }
});

2、使用方式:

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

disabled 建议不要绑定,我们可以通过调用组件的setDisabled方法来切换按钮可用状态;

second 初始值60s 没特别值可以不绑定;

所以我们可以在HTML页面这样:

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

JS这样:

var vm = new Vue({
  el:'#app',
  methods:{
    sendCode:function(){
      vm.$refs.timerbtn.setDisabled(true); //设置按钮不可用
      hz.ajaxRequest("sys/sendCode?_"+$.now(),function(data){
        if(data.status){
          vm.$refs.timerbtn.start(); //启动倒计时
        }else{
          vm.$refs.timerbtn.stop(); //停止倒计时
        }
      });
    },
  }
});

以上就是Vue 中怎么实现一个短信验证码组件,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue
AI