本文介绍了在Vuejs组件中使用Lodash编写异步函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要编写异步功能的函数,但我做不到正确的方法.希望你们能帮忙.

I have a function need to write async but I can't do it the right way. Hope your guys help.

async search (loading, search, vm) {
  let vm = this
  _.debounce(() => {
    let ApiURL = '/users/'
  }

  let { res } = await api.get(ApiURL) //Error
    vm.options = res.data
  }, 800)

推荐答案

只需将lodash函数直接指定为组件方法

Just assign the lodash function directly as a component method

new Vue({
    el: '#app',
    data: { requests: 0 },


  methods: {
    search: _.throttle(async function () {
      const res = await fetch('/echo/json/')
      this.requests++
      console.log(res)
    }, 1000)
  },


  created () {
    // 100ms interval but throttle works at 1000ms
    setInterval(() => {
        this.search()
    }, 100)
  }
})

https://jsfiddle.net/6thcxfym/

在您的情况下:

methods: {
    search: _.debounce(async function () {
      // this code may differ from your actual implementation
      const res = await api.get('/users/')
      this.options = res.data
    }, 1000)
  }
}

这篇关于在Vuejs组件中使用Lodash编写异步函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 10:48
查看更多