如何返回vue.js的“已创建”值

时间:2019-01-09 19:19:27

标签: javascript json vue.js

我正在获取天气小部件的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);
        });
      },
   })
});

2 个答案:

答案 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);
        });