【问题标题】:How do I get a plain array back from vuejs with a component?如何从带有组件的 vuejs 返回一个普通数组?
【发布时间】:2016-05-06 00:32:00
【问题描述】:

我正在使用对我的数据库的调用来检索一些结果并将它们推送到一个数组中。但是,当我console.log(this.activeBeers) 时,我没有得到一个数组而是一个对象。我怎样才能得到一个普通数组而不是一个对象?

Vue.component('beers', {
    template: '#beers-template',

    data: function() {
        return {
            activeBeers: []
        }
    },

    ready: function() {
        function getActiveBeers(array, ajax) {
            ajax.get('/getbeers/' + $('input#bar-id').val()).then(function (response) {
                $.each(response.data, function(key, value) {
                    array.push(value.id);
                });
            }, function (response) {
                console.log('error getting beers from the pivot table');
            });

            return array;
        }

        console.log(this.activeBeers = getActiveBeers(this.activeBeers, this.$http));
    },

    props: ['beers']
});

【问题讨论】:

    标签: javascript jquery arrays vue.js vue-resource


    【解决方案1】:

    AJAX 是异步完成的,因此您不能只返回您还没有的值。

    你应该在$.each 之后控制台记录你的东西,看看你收到了什么。

    【讨论】:

    • 我正在这样做已经检查了代码。该函数包含 $.each 循环,位于我记录实际数组的日志之前。除此之外,我仍然收到正确的值,除了它是一个对象而不是数组。
    【解决方案2】:

    正如其他答案所指出的,您的 getActiveBeers() 调用在填充数组的回调执行之前返回。

    你的数组是一个对象的原因是因为 Vue 在底层数据中包装/扩展数组,以便它可以拦截和响应任何变异方法——比如推送、弹出、排序等。

    您可以在 ready 函数的开头记录 this.activeBeers 以查看它是一个对象。

    顺便说一句,如果你想记录activeBeers的展开/纯数组,你可以使用你组件的$log方法:

    this.$log(this.activeBeers);
    

    【讨论】:

    • vuejs.org/api/#vm-log 这是 vm.$log 文档的链接。此命令降低了获取数据对象并将其表示为普通对象的复杂性。
    【解决方案3】:

    另一个答案是正确的,getActiveBeers 发送一个 HTTP 请求然后立即返回数组,它不等待 ajax 请求回来。您需要在ajax 请求的成功函数中处理activeBeers 的更新。您可以使用.bind() 函数确保成功函数中的this 引用Vue 组件,这样您就可以直接将id 推送到您的activeBeers 数组中。

    Vue.component('beers', {
        template: '#beers-template',
    
        data: function() {
            return {
                activeBeers: []
            }
        },
    
        ready: function() {
            this.getActiveBeers();
        },
    
        methods: {
            getActiveBeers: function(){
    
                this.$http.get('/getbeers/' + $('input#bar-id').val()).then(function (response) {
    
                    $.each(response.data, function(key, value) {
                        this.activeBeers.push(value.id);
                    }.bind(this));
    
                    console.log(this.activeBeers);
    
                }.bind(this), function (response) {
    
                    console.log('error getting beers from the pivot table');
    
                });
    
            }
        }
    
        props: ['beers']
    
    });
    

    【讨论】:

    • @Stephan-v 你能发布你看到的activeBeers 的值吗?
    • 啊,是的,我认为彼得的回答解释了这个问题。 Vue 变量实际上是带有get 函数的对象。因此,当您调用this.activeBeers 时,它会访问get 函数并为您提供一个数组。但实际的变量是一个对象。出于所有意图和目的,当您使用它时,它将是一个数组。
    猜你喜欢
    • 2017-12-22
    • 2020-08-03
    • 2018-08-18
    • 1970-01-01
    • 1970-01-01
    • 2018-05-16
    • 1970-01-01
    • 2019-06-12
    • 1970-01-01
    相关资源
    最近更新 更多