vue 倒计时功能实现详解,快来 get 灵感

Vue.js 实现倒计时功能
本文详细介绍了如何在Vue.js应用中实现倒计时功能,包括HTML模板、数据绑定、计算属性和方法的使用。通过设置定时器动态更新倒计时,并阻止用户在倒计时期间重复点击获取验证码按钮,提供更好的用户体验。

前言

当我们浏览网页时,常常会看到各种倒计时效果,比如秒杀倒计时、限时抢购倒计时等等,它们为我们带来了更好的用户体验和更强的营销效果。而如何实现这些倒计时效果呢?本文将带大家了解具体的倒计时实现方法。


实现思路

html 部分

根据 isCounting 的值来动态显示不同的文本和样式。当 isCountingtrue 时,按钮的背景色变为灰色,并且鼠标指针变为不可用;当 isCountingfalse 时,按钮的样式恢复为默认样式。

<template>
  <div>
    <input type="text" v-model="code" placeholder="请输入验证码" />
    <button class="notGainBox" :class="{ 'yesGainBox': isCounting }" @click="verification">{{ buttonText }}</button>
  </div>
</template>

data 部分

vuedata 中定义了几个变量,包括 isCountingcountdowncodeisCounting 用于表示是否正在倒计时,初始值为 falsecountdown 用于存储倒计时的秒数,初始值为 0code 用于存储用户输入的验证码。

data() {
  return {
    code: "", //输入框model绑定
    isCounting: false, //控制显示'获取按钮'还是'倒计时'
    countdown: 0, //计数器
  };
},

computed 部分

使用 setInterval 函数创建了一个定时器,每隔 1 秒执行一次回调函数。在回调函数中,将 countdown1,并判断是否倒计时结束。如果倒计时结束,清除定时器,并将 isCounting 设置为 false,表示倒计时结束。

buttonText() {
  return this.isCounting ? `${this.countdown}秒后重新获取` : "获取验证码";
},

methods 部分

在开始倒计时前,将 isCounting 设置为 true,表示正在倒计时。然后将 countdown 设置为 3,表示倒计时的初始值。
在点击获取验证码按钮的事件处理函数中,首先进行了一个条件判断,如果 isCountingtrue,则直接返回,防止用户重复点击。这样可以避免出现多个倒计时同时进行的情况。

methods: {
  verification() {
    if (this.isCounting) {
      return;
    }
    this.isCounting = true;
    this.countdown = 3; //赋值3秒
    const times = setInterval(() => {
      this.countdown--; //递减
      if (this.countdown === 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 ? `${this.countdown}秒后重新获取` : "获取验证码";
    },
  },
  methods: {
    verification() {
      if (this.isCounting) {
        return;
      }
      this.isCounting = true;
      this.countdown = 3; //赋值3秒
      const times = setInterval(() => {
        this.countdown--; //递减
        if (this.countdown === 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>

实现效果

在这里插入图片描述

<think>好的,用户想了解Vue和Spring Boot结合使用SSE的实现原理及用法,需要详细的教程和示例代码。首先,我需要回忆一下SSE的基本概念。SSE是服务器发送事件,允许服务器主动向客户端推送数据,基于HTTP长连接,适用于实时更新场景,比如股票价格、新闻推送等。 接下来,用户提到Vue和Spring Boot的结合,所以需要分两部分考虑:后端Spring Boot如何实现SSE,以及前端Vue如何接收和处理这些事件。根据引用[1],Spring Boot 3中使用响应式编程可以更高效地实现SSE,可能涉及WebFlux模块。但用户提供的引用中没有直接提到SSE的具体实现步骤,可能需要结合常规的Spring Boot知识。 首先,后端部分。Spring Boot中实现SSE通常使用SseEmitter类,这个类在Spring Web模块中。需要创建一个控制器,返回SseEmitter对象,并通过它发送事件。可能需要参考引用[2]中的依赖,比如Spring Web和可能涉及的安全性Spring Security,但用户的问题主要关注SSE,所以重点在创建控制器和发送事件。 然后前端Vue部分,需要使用EventSource API来连接SSE端点,监听消息事件。Vue组件中在生命周期钩子如mounted()中建立连接,处理接收到的数据,并更新响应式数据以触发视图更新。同时要注意在组件销毁时关闭连接,避免内存泄漏。 示例代码方面,后端需要创建一个REST控制器,返回SseEmitter,并异步发送数据。前端Vue组件中使用EventSource,处理onmessage事件,将数据绑定到data属性,并在模板中渲染。可能需要处理错误和连接关闭的情况,保证稳定性。 用户可能还会关心跨域问题,所以后端需要配置CORS,或者在Spring Security中允许相关端点。引用[2]提到了Spring Security的依赖,可能需要配置安全策略,但用户的问题可能不需要深入安全部分,除非特别提到。 另外,引用[3]提到Vue+Spring Boot的运行原理,开发流程是后端接口MVC开发,前端处理后端请求和渲染。SSE属于后端主动推送,所以前端需要持续监听,而不是传统的请求-响应模式。 总结步骤:后端创建SSE端点,使用SseEmitter发送事件;前端Vue使用EventSource连接,处理事件并更新界面。需要确保依赖正确,比如Spring Web,以及处理可能的跨域问题。示例代码需要展示基本实现,包括后端控制器的创建和前端Vue组件的集成。</think>### Vue与Spring Boot整合SSE实现详解 #### 一、技术原理 SSE(Server-Sent Events)基于HTTP协议实现服务器到客户端的单向通信,采用长连接机制保持通信通道。与WebSocket相比,SSE更轻量且天然支持断线重连[^1]。 技术实现流程: 1. 客户端通过`EventSource`建立SSE连接 2. Spring Boot使用`SseEmitter`对象管理连接 3. 服务器通过`send()`方法主动推送数据 4. Vue接收数据后触发响应式更新 #### 二、Spring Boot实现 1. 添加依赖(pom.xml) ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` 2. SSE控制器实现 ```java @RestController @RequestMapping("/sse") public class SseController { private final Map<String, SseEmitter> emitters = new ConcurrentHashMap<>(); @GetMapping("/connect") public SseEmitter connect() { SseEmitter emitter = new SseEmitter(3600_000L); // 设置1小时超时 String clientId = UUID.randomUUID().toString(); emitters.put(clientId, emitter); emitter.onCompletion(() -> emitters.remove(clientId)); emitter.onTimeout(() -> emitters.remove(clientId)); return emitter; } @Async public void sendData(String data) { emitters.forEach((id, emitter) -> { try { emitter.send(SseEmitter.event() .data(data) .id(id) .reconnectTime(5000)); } catch (IOException e) { emitter.complete(); emitters.remove(id); } }); } } ``` #### 三、Vue前端实现 1. 创建SSE连接组件 ```vue <template> <div> <h3>实时数据:{{ message }}</h3> </div> </template> <script> export default { data() { return { message: '', eventSource: null } }, mounted() { this.eventSource = new EventSource('http://localhost:8080/sse/connect'); this.eventSource.onmessage = (event) => { this.message = event.data; }; this.eventSource.onerror = (error) => { console.error('SSE连接错误:', error); this.eventSource.close(); }; }, beforeUnmount() { if (this.eventSource) { this.eventSource.close(); } } } </script> ``` #### 四、关键配置要点 1. 跨域处理(Spring Boot配置) ```java @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/sse/**") .allowedOrigins("http://localhost:8081") .allowedMethods("GET"); } } ``` 2. 心跳机制(防止连接超时) ```java @Scheduled(fixedRate = 30000) public void sendHeartbeat() { sendData("SYSTEM_HEARTBEAT:" + System.currentTimeMillis()); } ``` #### 五、应用场景示例 1. 实时股票行情推送 2. 物流状态跟踪 3. 即时新闻推送 4. 在线考试计时系统 $$ \text{通信可靠性公式:} R = 1 - \prod_{i=1}^{n}(1 - p_i) $$ 其中$p_i$表示单个消息的到达概率,$n$为消息重试次数
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

水星记_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值