【问题标题】:How to delay @keyup handler in Vue.js如何在 Vue.js 中延迟 @keyup 处理程序
【发布时间】:2018-09-17 13:59:58
【问题描述】:

我的看法:

ns-input#filterName(type="text", v-model="filterName", @keyup="searchTimeOut()")

在我的 vue 代码中:

getUsers() {
   .
   .
   .
   API.users.index(params).then(blabla);
   .
   .
   .
},

searchTimeOut() {
  let timeout = null;
  clearTimeout(timeout);
  // Make a new timeout set to go off in 800ms
  timeout = setTimeout(() => {
    this.getUsers();
    console.log("hi")
  }, 800);
},

我想在我停止打字和 800 毫秒后只给getUsers() 打电话一次。现在,我每次写信都会打电话给getUsers()

【问题讨论】:

  • @EmileBergeron .lazy 有什么帮助?
  • v-model.lazy 将仅在 change 事件上触发更改,这些事件在输入失去焦点时触发。也许它在您的特定情况下不起作用,但是当您想延迟 v-model 同步时可能会使用它。
  • 嗯,这与问题不太相关。这并不是真正的延迟。
  • @oniondomes 乍一看,并不清楚这是一个搜索建议输入,这就是我链接到lazy 和去抖动问题的原因。但是,.lazy 仍然是您想要在用户完成输入后“延迟”API 调用的常见解决方案。

标签: javascript vue.js vuejs2


【解决方案1】:

在清除间隔之前删除this.timer 值。改为这样做:

searchTimeOut() {  
    if (this.timer) {
        clearTimeout(this.timer);
        this.timer = null;
    }
    this.timer = setTimeout(() => {
        // your code
    }, 800);
}

【讨论】:

  • @tomatito 这个问题有很多通用的解决方案。你可以看看这个线程stackoverflow.com/a/1909508/9339801
  • 我认为您还需要为 keydown 制作一个处理程序。如果我输入 1 个字符,然后我长时间按下其他键或什至没有释放它会发生什么?
猜你喜欢
  • 2010-12-26
  • 2012-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多