Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am using a call to my database to retrieve some results and pushing them onto an array. However when I console.log(this.activeBeers) I don't get an array back but instead an object. How can I get a plain array back instead of a object?

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']
});
like image 262
Stephan-v Avatar asked Jan 28 '16 14:01

Stephan-v


2 Answers

AJAX is done asynchronously so you won't be able to just return the value that you do not have yet.

You should console.log your stuff after the $.each to see what you received.

like image 65
Andrius Avatar answered Sep 21 '22 17:09

Andrius


As the other answers pointed out, your getActiveBeers() call is returning before the callback that fills the array gets executed.

The reason your array is an object is because Vue wraps/extends arrays in the underlying data so that it can intercept and react to any mutating methods - like push, pop, sort, etc.

You can log this.activeBeers at the beginning of your ready function to see that it's an object.

By the way, if you want to log the unwrapped/plain array of activeBeers, you can use your component's $log method:

this.$log(this.activeBeers);
like image 28
Peter Avatar answered Sep 23 '22 17:09

Peter