如何使用组件从 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 是异步完成的,因此您将无法 return 您还没有的值。

您应该 console.log 在 $.each 之后查看您收到的东西。

另一个答案是正确的,getActiveBeers 发送一个 HTTP 请求,然后立即 returns 数组,它不会等待 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']

});

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

你的数组是一个对象的原因是因为 Vue wraps/extends 底层数据中的数组,因此它可以拦截并对任何变异方法做出反应 - 如推送、弹出、排序等。

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

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

this.$log(this.activeBeers);