最近做了一个小的demo,分享给大家,在很多地方都能用到。
一般获取短信验证码的时候会用到这个demo:
button里面包两个span标签,根据点击状态,显示不同的span,关键代码就是倒计时:
<div id="example"> <button @click="send"> <span v-if="sendMsgDisabled">{{time+'秒后获取'}}</span> <span v-if="!sendMsgDisabled">send</span> </button> </div>
button { width: 100px; height: 50px background: pink; }
var vm = new Vue({ el: '#example', data() { return { time: 60, // 发送验证码倒计时 sendMsgDisabled: false } }, methods: { send() { let me = this; me.sendMsgDisabled = true; let interval = window.setInterval(function() { if ((me.time--) <= 0) { me.time = 60; me.sendMsgDisabled = false; window.clearInterval(interval); } }, 1000); } } })