ajax 自调用函数到 vue 数据

ajax self invoked function to vue data

我正在尝试使用 自调用函数 进行 ajax 调用。 稍后我想使用响应在 Vue 中填充数据 属性,但由于某些原因我无法做到这一点。

这是我目前的代码

//chiamata Ajax a servizio
var getData = (function(){
  var req = $.ajax({
    type:'get',
    url:'https://api.myjson.com/bins/a8ohr',
    dataType: 'json',
    success: function(response)
    {
      result =JSON.parse(response);
    }
  });
  return {
    getResponse:function(){
      return req.success;   
    }
  }
}());

var modello = getData.getResponse(); 

我的目标是将 modello 作为 Vue 中的数据传递。

这里是VUE:

var Metromappa = new Vue({
  el: '#metromappa',
  data: {
    modello:modello
  },
  methods:{

  },
  beforeMount(){
    this.modello = modello;
  }
})

我做错了什么?

相反,您可以在 created() 生命周期挂钩中执行 ajax 调用并将数据 属性 modello 设置为那里的响应这个:

var Metromappa = new Vue({
            el: '#metromappa',
            data: {
                modello:null
            },
            methods:{

            },
            created(){
                var self = this;
                $.ajax({
                    type:'get',
                    url:'https://api.myjson.com/bins/a8ohr',
                    dataType: 'json',
                    success: function(response){
                        self.modello = response;
                    }
                });
            },

        })

这是jsFiddle

如果要分离逻辑:

var getData = function(){
            return $.ajax({
                    type:'get',
                    url:'https://api.myjson.com/bins/a8ohr',
                    dataType: 'json',
                    success: function(response){
                       console.log(response);
                    }
                });


        };




          var Metromappa = new Vue({
            el: '#metromappa',
                data: {
                    modello:null
                },
                 methods:{

                 },
                 beforeMount(){
                     var self = this;
                    getData().then(function(response){
                        self.modello = response;
                    }, function(error){});

                }
            })

这里是 updated fiddle

感谢 Bert Evans 指出我的错误