本篇文章給大家分享的是有關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 中怎么實現一個短信驗證碼組件,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。