使用vue 寫一個簡單的60s倒計(jì)時

在項(xiàng)目開發(fā)里,我們經(jīng)常會遇到發(fā)送驗(yàn)證碼、點(diǎn)擊了之后有60秒倒計(jì)時的按鈕,下面就看一下代碼如何寫?

<el-button @click="getCountdown" :disabled="totalTime <60">{{content}}</el-button>
            
export default {
    data() {
        return {
            totalTime: 60,
            content: "發(fā)送驗(yàn)證碼"
        }
    },
    methods: {
        getCountdown() {
            let clock =  window.setInterval(() => {
                this.content = this. totalTime + 's后重新發(fā)送';
                this.totalTime --;
                if(this. totalTime < 0){
                    this. totalTime = 60;
                    this.content = "重新發(fā)送驗(yàn)證碼";
                    window.clearInterval(clock);
                }
            }, 1000);
        }
    },
}

在data里分別用content和totalTime來記錄內(nèi)容和時間減1的操作,在countDown函數(shù)里我們用了setInterval定時器,每隔一秒totalTime減1,同時更改按鈕里顯示的內(nèi)容。在window.setInterval里用了箭頭函數(shù),因?yàn)樗鼤詣咏壎ㄍ饷娴膖his,所以就不用先存下this了

如圖所示:


image.png

image.png

image.png

設(shè)置button 的disabled是為了防止多次點(diǎn)擊出現(xiàn)倒計(jì)時速度變快的問題。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容