【问题标题】:How can I in Vue.js get axios response ( v-on:click ) (async / try,catch)?我如何在 Vue.js 中获得 axios 响应( v-on:click )(async / try,catch)?
【发布时间】:2021-04-24 00:36:04
【问题描述】:

有人可以帮助我,我正在尝试使用 try 和 catch 从异步函数中的 API whit axios 获取对象响应。 我收到:Promise {pending}。 我怎样才能得到我的对象?

在模板中:

<div class="div-search-city">
  <input v-model="inputCity" placeholder="insert city name"/>
  <button id="buttonCity" @click="get()">Search city</button>
</div>

在脚本中:

<script>
import myFunction from './js/service.js';

export default {
  name: 'Input',
  data () {
    return {
      myData: {}
    }
  },
  methods: {
    get(){
      this.myData = myFunction.axiosRequest(this.inputCity);
      console.log(this.myData);
    }
  }
}
</script>

这是我的 service.js 文件:

const axios = require('axios');

var myFunctions = {
  async axiosRequest(city){
    var options = {
        method: 'GET',
        url: 'https://api.waqi.info/feed/' + city + '/',
        params: {
            token: 'a1d2e0ee074e48f8bf....................'
        }
    };
    try {
      let response = await axios.request(options);
      return response
    }catch (error) {
       console.error(error)
    }
  }
}

export default myFunctions

谢谢。

【问题讨论】:

    标签: javascript api vue.js axios try-catch


    【解决方案1】:

    我这样做的方法是从 service.js 文件中返回承诺并在客户端中执行等待。在等待解决后,您可以将数据设置为Vue组件中的绑定变量。

    【讨论】:

    • 是的,它有效:我已经更改了 get() 函数 -> async get() 我已经更改了:this.myData = myFunction.axiosRequest(this.inputCity); to: this.myData = await myFunction.axiosRequest(this.inputCity);谢谢
    【解决方案2】:
    <script>
    import myFunction from './js/service.js';
    
    export default {
      name: 'Input',
      data () {
        return {
          Data: {},
          
        }
      },
      methods: {
        async get(){
          this.data = await myFunction.axiosRequest(this.inputCity);
          console.log(this.data);
          
        },
      }
      
    }
    </script>
    

    【讨论】:

      猜你喜欢
      • 2019-09-15
      • 1970-01-01
      • 2017-12-31
      • 2017-12-18
      • 1970-01-01
      • 2017-07-05
      • 2021-11-16
      • 2021-08-28
      • 2019-12-22
      相关资源
      最近更新 更多