[英]How to access an API with Vue.js?
我是JavaScript和Vue.js的新手,我在使用Vue.js訪問api時遇到了問題。 我正在嘗試訪問的API具有如下所示的JSON:
{
"coord": {
"lon": -88.99,
"lat": 40.51
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01n"
}
],
"base": "stations",
"main": {
"temp": 2.09,
"pressure": 1022.3,
"humidity": 69,
"temp_min": 2.09,
"temp_max": 2.09,
"sea_level": 1052.03,
"grnd_level": 1022.3
},
"wind": {
"speed": 12.66,
"deg": 205.502
},
"clouds": {
"all": 0
},
"dt": 1482203059,
"sys": {
"message": 0.186,
"country": "US",
"sunrise": 1482239741,
"sunset": 1482273134
},
"id": 4903780,
"name": "Normal",
"cod": 200
}
它上面的API鏈接是有效的,但是當我運行程序時,我不認為我正在訪問它。 即使我不嘗試解析JSON並只顯示從api收集的所有數據,我的變量仍然是空的。 所以,我必須做錯了才能訪問api。 此外,在訪問api之后,將像這樣工作解析它:例如,訪問標簽“temp”=>“data.main.temp”
var weather = new Vue({
el: '#weather',
data: {
getTemp: ''
},
created: function () {
this.fetchData();
},
methods: {
fetchData: function () {
this.$http.get('api.openweathermap.org/data/2.5/weather?q=Normal&units=imperial&APPID=MYAPPID'),
function (data) {
this.getTemp = data.main.temp;
}
}
}
})
;
HTML代碼 :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/vue.resource/1.0.3/vue-resource.min.js"></script>
</head>
<body>
<div id="weather">
{{getTemp}}
</div> <!--end of weather-->
</body>
<script src="app.js"></script>
</html>
我看到了this
范圍的問題, this
變化的范圍在$http.get
black里面,你需要進行以下更改:
methods: {
fetchData: function () {
var vm = this
this.$http.get('api.openweathermap.org/data/2.5/weather?q=Normal&units=imperial&APPID=MYAPPID'),
function (data) {
vm.getTemp = data.main.temp;
}
}
}
你也可以在這里查看我的類似答案。
我想在你的代碼中使用promises,以及其他一些調整
var weather = new Vue({
el: '#weather',
data: {
getTemp: []
},
created: function () {
this.fetchData();
},
methods: {
fetchData: function () {
this.$http.get('api.openweathermap.org/data/2.5/weather?q=Normal&units=imperial&APPID=MYAPPID')
.then(response => {
this.getTemp = response.data
// or like this this.getTemp = response.json()
})
}
}
})
;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.