基本的vue.js 2和vue-resource http得到变量赋值 [英] Basic vue.js 2 and vue-resource http get with variable assignment

查看:205
本文介绍了基本的vue.js 2和vue-resource http得到变量赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很难在vue.js 2中使用最基本的REST功能。

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

我想从某个端点获取数据并分配返回值到我的Vue实例的变量。这是我有多远。

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

在承诺中,我可以访问响应数据,但我似乎无法将其分配给用户或甚至是Vue实例的数据。

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.

毋庸置疑,我对vue.js完全陌生,并感谢任何帮助。

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

Stack: vue.js 2.03, vue-resource 1.0.3

干杯!

推荐答案

您可以创建一个对象并将其传递给vue实例,如下所示:

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

或者您可以在methods对象下创建一个函数,然后在挂载的函数中调用它:

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

这篇关于基本的vue.js 2和vue-resource http得到变量赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆