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

Vue computed属性内用let声明定时器实现输入防抖失效问题咨询

问题原因

你当前代码存在两个核心问题:

  1. 语法错误:计算属性strValue的对象定义中直接写let timer不符合JS对象字面量的结构要求,无法正常执行
  2. 作用域错误:即便语法修正,临时变量timer也无法跨多次set调用保留上一次的定时器ID,无法实现清除旧定时器的防抖效果

解决方案

将定时器ID挂载到Vue实例属性上存储即可,修改后代码如下:

computed: {
    ...mapGetters(['allDocumentTypeGroups', 'currentTicketCaseFiles', 'activeAttachmentIndex', 'showAttachmentsPreview', 'activeAttachments']),

    attachmentAcceptedLabel() {
      return this.attachmentAccepted ? this.t('accepted') : this.t('ignored');
    },
    attachmentAccepted: {
      get: function () {
        return !this.attachment.ignoreAttachment;
      },
      set: function (val) {
        return this.updateAttachment([this.attachment.id, { ignoreAttachment: !val }]);
      },
    },
    documentType: {
      get: function() {
        return this.attachment.documentTypeId;
      },
      set: function(val) {
        return this.updateAttachment([this.attachment.id, { documentTypeId: val }]);
      },
    },
    approveAttachment: {
      get: function() {
        return this.attachment.approvedAttachment;
      },
      set: function(val) {
        return this.updateAttachment([this.attachment.id, { approvedAttachment: val }]);
      },
    },
    strValue: {
      get: function () {
        return this.attachment.strValue;
      },
      set: function (val) {
        // 清除上一次的定时器
        if(this.updateTimer){
          clearTimeout(this.updateTimer);
        }
        // 新定时器ID存到实例属性上
        this.updateTimer = setTimeout(() => { 
          this.updateAttachment([this.attachment.id, { strValue: val }]) 
        }, 8000);
      },
    },
},
// 补充组件销毁钩子,避免内存泄漏
beforeDestroy() {
  if(this.updateTimer) {
    clearTimeout(this.updateTimer)
  }
}

修改说明

  • 定时器ID存放在实例的updateTimer属性上,多次触发strValue的set方法时可以读取到上一次的定时器ID完成清除
  • 使用箭头函数省去额外的self变量声明,直接指向Vue实例
  • 补充了组件销毁时的定时器清除逻辑,避免组件销毁后定时器仍触发导致的报错
  • 可根据实际需求调整防抖延迟(当前8秒时间较长,常规输入防抖建议设置为300~1000毫秒)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 16:54:03