5

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

3 回答 3

2

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

你应该 console.log 你的东西之后$.each看看你收到了什么。

于 2016-01-28T15:57:52.767 回答
2

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

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

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

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

this.$log(this.activeBeers);
于 2016-01-28T18:09:44.783 回答
1

另一个答案是正确的,getActiveBeers发送一个 HTTP 请求然后立即返回数组,它不等待 ajax 请求回来。您需要activeBeers在 ajax 请求的成功函数中处理更新。您可以使用该.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']

});
于 2016-01-28T16:37:15.270 回答