Vue computed属性内用let声明定时器实现输入防抖失效问题咨询
问题原因
你当前代码存在两个核心问题:
- 语法错误:计算属性
strValue的对象定义中直接写let timer不符合JS对象字面量的结构要求,无法正常执行 - 作用域错误:即便语法修正,临时变量
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
相关产品推荐
相关产品推荐

