ajax self invoked function to vue data

Pds Ink

I'm trying to use a self invoked function to do an ajax call. Later I want to use the response to populate a data property inside Vue, but for some reason I'm not able to do that.

Here is my code so far

//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(); 

My goal is to pass modello as data in Vue.

Here the VUE:

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

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

What have I done wrong?

Vamsi Krishna

Instead you can perform the ajax call in the created() lifecycle hook and set the data property modello to the response there like this:

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;
                    }
                });
            },

        })

Here is the jsFiddle

If you want to seperate the logic:

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){});

                }
            })

here is the updated fiddle

thanks to Bert Evans for pointing out my mistake

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related