繁体   English   中英

我如何在 Vue.js 中获得 axios 响应(v-on:click)(异步/尝试,捕获)?

[英]How can I in Vue.js get axios response ( v-on:click ) (async / try,catch)?

Someone can help me, i'm trying to get object response from API whit axios in async function with try and catch. 我收到:Promise { 待定}。 我怎样才能得到我的 object?

在模板中:

<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

谢谢。

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

<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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM