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

});


<timer-btn ref="timerbtn" class="btn btn-default" v-on:run="sendCode" ></timer-btn>
 
 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短信验证码登录实现 #### 后端逻辑处理 在后端部分,当接收到请求时,在业务层生成随机字符串作为验证码,并通过调用第三方服务完成实际的消息发送操作。为了保证安全性与有效性,通常会将此验证码存储于缓存数据库如Redis内一定时间范围以便后续验证[^1]。 ```python import random import redis def send_verification_code(phone_number): code = ''.join([str(random.randint(0, 9)) for _ in range(6)]) # Generate a six-digit verification code rds = redis.Redis(host='localhost', port=6379, db=0) try: # Store the generated code into Redis with an expiration time of five minutes. rds.setex(f'verification:{phone_number}', 300, code) # Call SMS sending tool class method to actually send out the message (omitted here). return True except Exception as e: print(e) return False ``` #### 前端Vue组件设计 对于前端而言,则需创建专门用于展示和交互的Vue组件来负责发起获取验证码请求、倒计时控制等功能。这里可以通过`axios`库来进行HTTP通信;利用定时器机制管理按钮状态变化及等待期间的文字提示更新等行为[^3]。 ```html <template> <div id="verification-code"> <!-- Other form elements --> <button @click.prevent="requestCode()" :disabled="isCounting">{{ buttonText }}</button> <!-- Rest parts omitted --> </div> </template> <script> export default { data() { return { phoneNumber: '', remainingTime: 0, intervalId: null, }; }, computed: { isCounting() {return this.remainingTime > 0;}, buttonText(){ if(this.isCounting){ return `${this.remainingTime}s later resend`; }else{ return 'Get Verification Code'; } } }, methods: { async requestCode() { const response = await axios.post('/api/sendVerificationCode', {phoneNumber:this.phoneNumber}); if(response.data.success === true){ let countDownSeconds = 60; clearInterval(this.intervalId); this.remainingTime = countDownSeconds; this.intervalId = setInterval(() => { if (--countDownSeconds >= 0) { this.remainingTime = countDownSeconds; } else { clearInterval(this.intervalId); } }, 1000); } // Handle error cases... } } } </script> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值