首页 > 解决方案 > 从 API 密钥获取温度数据

问题描述

我正在尝试从 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>

标签: vue.jsvuejs2axios

解决方案


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

  1. 将完整的 URL 输入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>


推荐阅读