【问题标题】:Basic vue.js 2 and vue-resource http get with variable assignment基本 vue.js 2 和 vue-resource http 获取变量赋值
【发布时间】:2017-02-25 10:30:28
【问题描述】:

我真的很难让最基本的 REST 功能在 vue.js 2 中工作。

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

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

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

不用说,我对 vue.js 完全陌生,感谢您的帮助。

堆栈:vue.js 2.03,vue-resource 1.0.3

干杯!

【问题讨论】:

    标签: javascript vue.js vue-resource


    【解决方案1】:

    您可以像这样创建一个对象并将其传递给 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 
    });
    

    或者你可以在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();
        }
    });
    

    【讨论】:

    • 非常感谢您的回答,效果很好!但这种行为背后的原因是什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-13
    • 2017-04-01
    • 2017-05-27
    • 2018-03-03
    • 1970-01-01
    • 2017-04-21
    相关资源
    最近更新 更多