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(); //停止倒计时
                }
            });
        },
    }
});

转载自:https://my.oschina.net/woter/blog/835753?hmsr=toutiao.io

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值