如何使用组件从 vuejs 中获取纯数组

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

本文关键字:获取 数组 vuejs 何使用 组件      更新时间:2023-09-26

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

AJAX 是异步完成的,因此您将无法只返回尚未具有的值。

你应该在$.each后安慰.log你的东西,看看你收到了什么。

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

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

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

顺便说一下,如果你想记录activeBeers的解包/纯数组,你可以使用组件的$log方法:

this.$log(this.activeBeers);

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