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

Ste*_*n-v 5 javascript arrays jquery vue.js vue-resource

我正在使用对我的数据库的调用来检索一些结果并将它们推送到数组上.但是,当我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']
});
Run Code Online (Sandbox Code Playgroud)

Jef*_*eff 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']

});
Run Code Online (Sandbox Code Playgroud)