如何在异步功能上使用反跳功能?

ST8*_*T80 1 javascript debouncing vue.js vuejs2 debounce

如何debounceasync功能上使用?我的vue-app中有一个方法,该方法可从API检索数据,该方法连续调用该API,而我想避免这种情况。

这是我的方法:

methods: {
    async getAlbums () {
     const response = await AlbumService.fetchAlbums()
     this.albums = response.data.albums
    } 
}
Run Code Online (Sandbox Code Playgroud)

我以前已经安装了,lodash那么如何实现呢?

Vam*_*hna 6

Lodash的debounce函数接受一个函数,等待时间并返回一个函数。

所以这样做:

methods: {
  getAlbums: _.debounce(async function() {
    const response = await AlbumService.fetchAlbums();
    this.albums = response.data.albums;
  }, 1000);
}
Run Code Online (Sandbox Code Playgroud)

  • 仅当 lodash debounceleading 选项设置为 true 时才有效。 (7认同)
  • @user1843640 抱歉劫持了一条旧评论,但它是否有理由只与“leading : true”一起使用?对我来说,这会导致不需要的行为,例如如果用户在搜索字段中输入“搜索”,那么它只会在“s”上进行搜索 (4认同)
  • 与await一起使用时似乎无法正确返回值 (2认同)