节流
节流(throttle):当持续触发事件时,保证一定时间段内只调用一次事件处理函数
vue项目 验证码登录--以及倒计时
<template> <button @click="handleCaptcha">{{captcha}}</button> </template> <script> export default { name: "Login", data() { return { captcha: "获取验证码", totalTime: 60, canClick: true, // 节流 clockTimer: null, // 定时器 } }, methods: { handleCaptcha() { if (!this.canClick) return // 节流 防止频繁访问接口 this.canClick = false console.log('进入倒计时...') this.captcha = this.totalTime + 's后重新发送' let that = this that.clockTimer = window.setInterval(() => { that.totalTime-- that.captcha = that.totalTime + 's后重新发送' if (that.totalTime < 0) { window.clearInterval(that.clockTimer) that.captcha = '重新发送验证码' that.totalTime = 60 that.canClick = true } },1000) }, } } </script>