[Vuejs]-Ajax self invoked function to vue data

0👍

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

Leave a comment