繁体   English   中英

如何从带有组件的vuejs中获取纯数组?

[英]How do I get a plain array back from vuejs with a component?

我正在使用对数据库的调用来检索一些结果并将其推入数组。 但是,当我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']
});

AJAX是异步完成的,因此您将无法仅返回尚未拥有的值。

您应该在$.each之后用console.log记录您的内容,以查看收到的内容。

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

您的数组是对象的原因是因为Vue在基础数据中包装/扩展了数组,以便Vue可以拦截和响应任何变异方法,例如push,pop,sort等。

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

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

this.$log(this.activeBeers);

另一个答案是正确的, 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']

});

暂无
暂无

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

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