Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I'm really struggling to get the most basic REST functionality to work in vue.js 2.

I'd like to get data from some endpoint and assign the returned value to a variable of my Vue instance. Here's how far I got.

var link = 'https://jsonplaceholder.typicode.com/users';
var users;

Vue.http.get(link).then(function(response){
    users = response.data;
}, function(error){
    console.log(error.statusText);
});

new Vue ({
    el: '#user-list',
    data: {
        list: users
    }
});

Inside the promise, I can access the response data, but I cannot seem to assign it to users or even to data of the Vue instance.

Needless to say, I'm completely new to vue.js and thankful for any help.

Stack: vue.js 2.03, vue-resource 1.0.3

Cheers!

share|improve this question
up vote 1 down vote accepted

You can create an object and pass it to the vue instance like that :

var link = 'https://jsonplaceholder.typicode.com/users';
var data = { 
    list: null 
};

Vue.http.get(link).then(function(response){
    data.list = response.data;
}, function(error){
    console.log(error.statusText);
});

new Vue ({
    el: '#app',
    data: data 
});

Or you can create a function under the methods object and then call it in the mounted function :

var link = 'https://jsonplaceholder.typicode.com/users';
new Vue ({
    el: '#app',
    data: {
        list: null
    },
    methods:{
        getUsers: function(){
            this.$http.get(link).then(function(response){
                this.list = response.data;
            }, function(error){
                console.log(error.statusText);
            });
        }
    },
    mounted: function () {
        this.getUsers();
    }
});
share|improve this answer
1  
Thank you very much for your answer, it works perfectly! But what is the reason behind this behavior? – Robin Löffel Oct 16 at 12:19
    
look at http://vuejs.org/api/#data hope it helps. – ABDEL-RHMAN Oct 16 at 12:24

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.