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 に答える
1

他の答えは正しく、getActiveBeersHTTP リクエストを送信してからすぐに配列を返します。ajax リクエストが返されるのを待ちません。activeBeersajax リクエストの成功関数での更新を処理する必要があります。この.bind()関数を使用しthisて、成功した関数がコンポーネントを参照していることを確認できます。これにより、ID を配列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']

});
于 2016-01-28T16:37:15.270 に答える