How to get a simple array from vuejs with a component?

I use my database call to get some results and push them to an array. However, when I console.log(this.activeBeers), I do not get the array back, but instead an object. How can I get a simple array instead of an 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']
});
+4
source share
3 answers

, getActiveBeers HTTP-, , ajax. activeBeers ajax. .bind(), , this Vue, 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']

});
+1

AJAX , , .

, , console.log $.each.

+2

, getActiveBeers() , , , .

, , , Vue / , - push, pop, sort ..

You can write this.activeBeersat the beginning of your function readyto see that it is an object.

By the way, if you want to register a deployed / simple array activeBeers, you can use your component $log:

this.$log(this.activeBeers);
+2
source

Source: https://habr.com/ru/post/1626370/


All Articles