美文网首页
使用vue 写一个简单的60s倒计时

使用vue 写一个简单的60s倒计时

作者: cesiuming | 来源:发表于2020-11-18 17:27 被阅读0次

在项目开发里,我们经常会遇到发送验证码、点击了之后有60秒倒计时的按钮,下面就看一下代碼如何写?

<el-button @click="getCountdown" :disabled="totalTime <60">{{content}}</el-button>
            
export default {
    data() {
        return {
            totalTime: 60,
            content: "发送验证码"
        }
    },
    methods: {
        getCountdown() {
            let clock =  window.setInterval(() => {
                this.content = this. totalTime + 's后重新发送';
                this.totalTime --;
                if(this. totalTime < 0){
                    this. totalTime = 60;
                    this.content = "重新发送验证码";
                    window.clearInterval(clock);
                }
            }, 1000);
        }
    },
}

在data里分别用content和totalTime来记录内容和时间减1的操作,在countDown函数里我们用了setInterval定时器,每隔一秒totalTime减1,同时更改按钮里显示的内容。在window.setInterval里用了箭头函数,因为它会自动绑定外面的this,所以就不用先存下this了

如图所示:


image.png
image.png
image.png

设置button 的disabled是为了防止多次点击出现倒计时速度变快的问题。

相关文章

网友评论

      本文标题:使用vue 写一个简单的60s倒计时

      本文链接:https://www.haomeiwen.com/subject/spwciktx.html