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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM