Write async function with Lodash in a Vuejs compon

2019-02-21 04:57发布

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)

1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-02-21 05:26

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/

In your case:

methods: {
    search: _.debounce(async function () {
      // this code may differ from your actual implementation
      const res = await api.get('/users/')
      this.options = res.data
    }, 1000)
  }
}
查看更多
登录 后发表回答