【问题标题】:How to dynamic call the axios method in VueJS/NuxtJsVueJS/NuxtJs中如何动态调用axios方法
【发布时间】:2021-07-02 20:18:44
【问题描述】:

我正在尝试优化我的代码。所以,我动态使用了 axios 函数,但是返回的响应是一个待处理的console log。我正在使用async/await。任何人都可以帮助我。

这是我的代码:

methods: {
  getAgentsNames() {
    const data = this.callAxios('get', `/getAllAgents`)
    console.log(data) // returns pending
    this.agents = data.listings
  },

  async callAxios(method, url, paramsBody = null) {
    try {
      const response = await this.$axios({
        method,
        url,
        params: paramsBody,
        headers: this.headers,
      })
      console.log(response) // success and have response data.
      if (response.data.status == 'ok') {
        return response.data
      } else {
        ifNotOK(response, this.$cookies)
        return null
      }
    } catch (error) {
      console.log(error)
      return null
    }
  },
},

【问题讨论】:

    标签: javascript vue.js vuejs2 axios nuxt.js


    【解决方案1】:

    你的顶层函数也需要等待调用返回:

    async getAgentsNames() {
                    let data = await this.callAxios(
    

    【讨论】:

    • 感谢它的工作,。我现在可以优化代码了
    猜你喜欢
    • 2019-10-26
    • 2018-06-30
    • 2019-01-09
    • 1970-01-01
    • 2018-06-25
    • 1970-01-01
    • 2020-08-17
    • 2021-10-28
    • 2020-06-14
    相关资源
    最近更新 更多