vue.js - 从 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>
解决方案
我调整了以下项目,然后似乎工作正常。
将完整的 URL 输入
axios.get
喜欢${this.base_url}weather?
不确定
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>
推荐阅读
- flutter - 在颤动的输入字段上键入时如何更改文本字段
- ios - 如何将与现实世界对象的碰撞应用到 RealityKit 中的 3D 对象 (.usdz)?
- laravel - Laravel:电子邮件未从服务器发送
- java - Java PriorityQueue Comparator 在特定条件下插入二维数组
- javascript - 如何使用 each 和 image.onload 保留数组的顺序
- javascript - api在axios中被阻止
- python - 如何使用 python 脚本在没有熊猫的情况下进行 vlookup
- window - 如何创建具有多个条件计数的 siddhi 应用程序
- html - 配售里面的标签
- html - 使用 flexbox 修复标题和侧边栏,无需手动设置偏移边距