【问题标题】:Get temperature data from API key从 API 密钥获取温度数据
【发布时间】:2020-09-01 20:53:46
【问题描述】:

我正在尝试从 api 获取温度数据。我无法让它工作。我做错了什么?在显示结果的 div 中是否需要 v-for 或其他内容?

new Vue({
  el: "#app",
  data () {
  return {
  api_key: 'adf173dfdcd1a6aea78ba12651a19177',
    base_url: 'https://api.openweathermap.org/data/2.5/',
    weather: {},
    query: ''  
  }
   },
  methods: {
    grabWeather() {
        axios.get(`api.openweathermap.org/data/2.5/weather?id=${this.query}&appid=${this.api_key}`)
      .then(response => {
        this.weather = response.data;
      })
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.20.0/axios.min.js"></script>
<div id="app">
  <h2>Temperature:</h2>
  <input type="text" v-model="query">
  
 <div>
   {{weather.name}}
   {{weather.temp}}

 </div>
  <button @click="grabWeather">
  Grab
  </button>

</div>

【问题讨论】:

  • 您不应在帖子中包含 API 密钥。

标签: vue.js vuejs2 axios


【解决方案1】:

我调整了以下项目,然后似乎工作正常。

  1. 将完整网址输入axios.get,如${this.base_url}weather?

  2. 不知道查询参数的the parameter=id是什么意思,我大致阅读了api.openweathermap.com中的用户指南,然后将其更改为q=${this.query}(它将查询天气信息一城市名称)。

new Vue({
  el: "#app",
  data () {
  return {
  api_key: 'adf173dfdcd1a6aea78ba12651a19177',
    base_url: 'https://api.openweathermap.org/data/2.5/',
    weather: {},
    query: 'San Jose'  
  }
   },
  methods: {
    grabWeather() {
        axios.get(`${this.base_url}weather?q=${this.query}&appid=${this.api_key}`)
      .then(response => {
        this.weather = response.data;
      })
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.20.0/axios.min.js"></script>
<div id="app">
  <h2>Temperature:</h2>
  <input type="text" v-model="query">
  
 <div>
   <p>{{weather.name}}</p>
   <pre>{{weather.main}}</pre>

 </div>
  <button @click="grabWeather">
  Grab
  </button>

</div>

【讨论】:

    猜你喜欢
    • 2021-12-11
    • 2018-08-22
    • 2013-03-02
    • 1970-01-01
    • 1970-01-01
    • 2015-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多