一、 页面结构
假设你有一个发送短信按钮,点击按钮时会触发发送短信并启动倒计时。
<template><view><button @click="sendSms" :disabled="isSending">{{ buttonText }}</button></view>
</template>
二、脚本部分
在脚本中,定义一个倒计时的变量 time 和控制按钮状态的 isSending。
<script>
export default {data() {return {isSending: false, // 是否正在发送短信time: 60, // 倒计时时间buttonText: '发送验证码' // 按钮文本};},methods: {// 发送短信的方法sendSms() {if (this.isSending) return; // 防止重复点击this.isSending = true; // 设置为发送状态this.buttonText = `${this.time}s后重新获取`;// 启动倒计时const countdown = setInterval(() => {this.time--;this.buttonText = `${this.time}s后重新获取`;// 如果倒计时结束if (this.time <= 0) {clearInterval(countdown); // 清除定时器this.isSending = false; // 恢复按钮this.time = 60; // 重置倒计时this.buttonText = '发送验证码'; // 重置按钮文本}}, 1000);// 这里可以调用发送短信的接口// 假设发送短信成功后,继续倒计时// this.sendSmsApi();}}
};
</script>
三、样式部分(可选)
你可以为按钮和倒计时文本添加一些简单的样式,使其更直观。
<style scoped>
button {background-color: #007aff;color: #fff;padding: 10px 20px;border-radius: 5px;
}button:disabled {background-color: #b0b0b0;
}
</style>
说明:
isSending 控制按钮是否可点击,防止用户在倒计时期间重复点击。
time 用于记录倒计时的秒数,从 60 秒开始。
每秒通过 setInterval 更新按钮文本,并在倒计时结束时恢复原状态。
sendSms 方法负责触发发送短信和启动倒计时。