简体   繁体   English

基本的vue.js 2和vue-resource http得到变量赋值

[英]Basic vue.js 2 and vue-resource http get with variable assignment

I'm really struggling to get the most basic REST functionality to work in vue.js 2. 我真的很难在vue.js 2中使用最基本的REST功能。

I'd like to get data from some endpoint and assign the returned value to a variable of my Vue instance. 我想从某个端点获取数据并将返回的值分配给我的Vue实例的变量。 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. 在promise中,我可以访问响应数据,但我似乎无法将其分配给用户甚至是Vue实例的数据。

Needless to say, I'm completely new to vue.js and thankful for any help. 毋庸置疑,我对vue.js全新,并感谢任何帮助。

Stack: vue.js 2.03, vue-resource 1.0.3 Stack:vue.js 2.03,vue-resource 1.0.3

Cheers! 干杯!

You can create an object and pass it to the vue instance like that : 您可以创建一个对象并将其传递给vue实例,如下所示:

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 : 或者您可以在methods对象下创建一个函数,然后在挂载的函数中调用它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM