当我们浏览网页时,常常会看到各种倒计时效果,比如秒杀倒计时、限时抢购倒计时等等,它们为我们带来了更好的用户体验和更强的营销效果。而如何实现这些倒计时效果呢?本文将带大家了解具体的倒计时实现方法。
html
部分
根据 isCounting
的值来动态显示不同的文本和样式。当 isCounting
为 true
时,按钮的背景色变为灰色,并且鼠标指针变为不可用;当 isCounting
为 false
时,按钮的样式恢复为默认样式。
<template><div><input type="text" v-model="code" placeholder="请输入验证码" /><button class="notGainBox" :class="{ 'yesGainBox': isCounting }" @click="verification">{{ buttonText }}</button></div>
</template>
data
部分
在 vue
的 data
中定义了几个变量,包括 isCounting
、countdown
和 code
。isCounting
用于表示是否正在倒计时,初始值为 false
;countdown
用于存储倒计时的秒数,初始值为 0
;code
用于存储用户输入的验证码。
data() {return {code: "", //输入框model绑定isCounting: false, //控制显示'获取按钮'还是'倒计时'countdown: 0, //计数器};
},
computed
部分
使用 setInterval
函数创建了一个定时器,每隔 1
秒执行一次回调函数。在回调函数中,将 countdown
减 1
,并判断是否倒计时结束。如果倒计时结束,清除定时器,并将 isCounting
设置为 false
,表示倒计时结束。
buttonText() {return this.isCounting ? `${untdown}秒后重新获取` : "获取验证码";
},
methods
部分
在开始倒计时前,将 isCounting
设置为 true
,表示正在倒计时。然后将 countdown
设置为 3
,表示倒计时的初始值。
在点击获取验证码按钮的事件处理函数中,首先进行了一个条件判断,如果 isCounting
为 true
,则直接返回,防止用户重复点击。这样可以避免出现多个倒计时同时进行的情况。
methods: {verification() {if (this.isCounting) {return;}this.isCounting = untdown = 3; //赋值3秒const times = setInterval(() => {untdown--; //递减if (untdown === 0) {// === 0 变成获取按钮clearInterval(times);this.isCounting = false;}}, 1000);},
},
css部分代码
<style scoped>
/* input输入框样式 */
input {width: 200px;padding: 0px 10px;height: 36px;border: none;border-radius: 4px;border: 1px solid #ccc;margin-right: 8px;
}/* 默认获取验证码按钮样式 */
.notGainBox {border: none;background: #ff5000;color: #fff;height: 36px;padding: 0px 14px;border-radius: 4px;cursor: pointer;
}
/* 点击后获取验证码按钮样式 */
.yesGainBox {background: #ccc;cursor: not-allowed;
}
</style>
<template><div><input type="text" v-model="code" placeholder="请输入验证码" /><button class="notGainBox" :class="{ 'yesGainBox': isCounting }" @click="verification">{{ buttonText }}</button></div>
</template><script>
export default {data() {return {code: "", //输入框model绑定isCounting: false, //控制显示'获取按钮'还是'倒计时'countdown: 0, //计数器};},computed: {buttonText() {return this.isCounting ? `${untdown}秒后重新获取` : "获取验证码";},},methods: {verification() {if (this.isCounting) {return;}this.isCounting = untdown = 3; //赋值3秒const times = setInterval(() => {untdown--; //递减if (untdown === 0) {// === 0 变成获取按钮clearInterval(times);this.isCounting = false;}}, 1000);},},
};
</script><style scoped>
/* input输入框样式 */
input {width: 200px;padding: 0px 10px;height: 36px;border: none;border-radius: 4px;border: 1px solid #ccc;margin-right: 8px;
}/* 默认获取验证码按钮样式 */
.notGainBox {border: none;background: #ff5000;color: #fff;height: 36px;padding: 0px 14px;border-radius: 4px;cursor: pointer;
}
/* 点击后获取验证码按钮样式 */
.yesGainBox {background: #ccc;cursor: not-allowed;
}
</style>
本文发布于:2024-01-31 18:59:01,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170669874430660.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |