You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js如何实现监听输入值5秒内未发生变化的功能?

实现方案

核心采用防抖逻辑实现5秒无变更监听:

  • 新增变量存储定时器ID,每次OTP值变化时先清空旧定时器,再开启新的5秒倒计时
  • 弹窗打开时就启动首次倒计时,覆盖初始未输入的状态
  • 弹窗关闭、用户提交OTP时主动清除定时器,避免内存泄漏和误触发

修改后完整代码如下:

<template>
 <div>
  <input type="text" v-model="otp">
  <b-button size="md" @click="cancel()" class="jump-to-ada-btn-cancel">
    Cancel
  </b-button>
  <b-button size="md" @click="handleJumpPage()" class="jump-to-ada-btn">
    Send
  </b-button>
 </div>
</template>

<script>
export default {
  data () {
    return {
      otp: "",
      // 存储定时器ID
      otpTimeoutTimer: null
    }
  },
  computed: {
    show: {
      get: function () {
        return this.$store.state.modals.showOTPModal
      },
      set: function (val) {
        this.$store.commit("OPEN_OTP", {fieldName: "showOTPModal", fieldValue: val})
      }
    }
  },
  mounted() {
    // 组件挂载时如果弹窗已打开,启动定时器
    if (this.show) {
      this.startOtpTimer()
    }
  },
  beforeDestroy() {
    // 组件销毁时清除定时器
    this.clearOtpTimer()
  },
  watch: {
    // 监听弹窗显示状态,打开时启动定时器,关闭时清除
    show(newVal) {
      if (newVal) {
        this.startOtpTimer()
      } else {
        this.clearOtpTimer()
      }
    },
    otp: function() {
      // 值变化时先清除旧定时器,再重新启动
      this.clearOtpTimer()
      this.startOtpTimer()
    }
  },
  methods: {
    // 启动OTP无变更倒计时
    startOtpTimer() {
      this.otpTimeoutTimer = setTimeout(() => {
        // 5秒无变更触发逻辑,可替换为你实际的断开连接逻辑
        alert("OTP超过5秒未变更,已断开连接")
        this.cancel()
      }, 5000)
    },
    // 清除定时器
    clearOtpTimer() {
      if (this.otpTimeoutTimer) {
        clearTimeout(this.otpTimeoutTimer)
        this.otpTimeoutTimer = null
      }
    },
    checkValueChange(newValue) {
      if(newValue === "") {
        alert("value is not changed yet")
      }
    },
    cancel() {
      this.show = false
      // 取消时清除定时器
      this.clearOtpTimer()
      // 补充你其他的取消逻辑
    },
    handleJumpPage() {
      // 提交OTP时清除定时器,避免提交后还触发超时逻辑
      this.clearOtpTimer()
      // 补充你其他的提交逻辑
    }
  }
}
</script>

内容的提问来源于stack exchange,提问作者OSW

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 08:15:07