我正在获取天气小部件的api json数据。返回null。我很好地获取json数据。但是我无法处理这个值。
这是我的html;
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script type="text/javascript" src="./js/jquery-3.3.1.min.js"></script>
</head>
<body>
<script>
/* $(document).ready(function(){
$.getJSON(url, function(json){
console.log(json.location.name);
})
})/*/
</script>
<div id="app" >{{Country}}</div>
<p v-if="isLoading">Loading</p>
<script type="text/javascript" src="./js/app.js"></script>
</body>
</html>
这是我的js;
window.addEventListener('load',()=>{
var app = new Vue ({
el: '#app',
data:{
Country : null,
Temp : null,
Icon : null,
isLoading : true,
},
created(){
var url ="http://api.apixu.com/v1/current.json?key=a69259fba9904700964121622190801&q=Nazilli";
$.getJSON(url,function(json){
console.log(json);
this.isLoading = false;
this.Country = json.location.name;
console.log(this.Country);
});
},
})
});
答案 0 :(得分:1)
您在this
回调中丢失了$.getJSON
上下文:它没有指向函数调用内的Vue实例。
您应将this
绑定以直接运行:
$.getJSON(url, (function (json) {
//...
}).bind(this));
或使用胖箭头功能:
$.getJSON(url, (json) => {
//...
});
答案 1 :(得分:0)
this
的范围在getJSON函数中更改。
您必须保存父this
var url ="http://api.apixu.com/v1/current.json?key=a69259fba9904700964121622190801&q=Nazilli";
var me = this; // save this in me variable
$.getJSON(url,function(json){
console.log(json);
me.isLoading = false;
me.Country = json.location.name; // use me instead this
console.log(me.Country);
});