Array push - getting empty object in array

Hi

Could anyone please tell me why I’m getting the array with empty object here - it’s vuejs

var Pizza = Vue.extend({

    template: '#pizza-template',

    data() {

        return {
            
            item: [
                { name: 'Margarita', price: 10 }
            ],

            bag: []

        };

    },

    methods: {

        addToBag(item) {

            this.bag.push({
                name: item.name,
                price: item.price
            }); 

        }

    },


});

Thanks.

That quoted section looks to be the main cause of the problem. I think that you are instead wanting:

data: function () {

A similar situation will apply to the addToBag section too.

Hey Paul

I did it in ES2015 way, tried with “normal” way but no luck.

Syntactically the code works well as it is. I don’t have Vue currently, but passing the object to a fake extend method results in it being successfully output to the console:

<script>
var Vue = {
    extend(obj) {
        console.log(obj); // successful output of template methods and data
    }
};
var Pizza = Vue.extend({
    template: '#pizza-template',
    data() {
        return {
            item: [
                { name: 'Margarita', price: 10 }
            ],
            bag: []
        };
    },
    methods: {
        addToBag(item) {
            this.bag.push({
                name: item.name,
                price: item.price
            });
        }
    }
});
</script>

Yes, but take look at this

Yes, there’s the margarita, and the bag.

Sorry don’t understand what you want to say.

The margarita should be into bag array, when user fire addToBag method.

Excellent. Thank you very much. I may not be the man to help you with that as I have no experience with Vue, but we do now have enough information (thank you) for someone else to help you with this issue.

All I can suggest is that instead of pusing a new object:

        addToBag(item) {
            this.bag.push({
                name: item.name,
                price: item.price
            });
        }

You will instead need to push the data() object.

        addToBag(item) {
            this.bag.push(
                // some way to run the data() method
            );
        }
1 Like

Sorry for bad explanation, I was in hurry so just now I noticed that I didn’t give any info about my problem.

So it’s here:

As you see I have one fake item array that contain object (in this case the product), and one empty array bag (shopping cart) where I want the store selected item - below is addToBag method that should add product to the bag array after clicking on button, but for some reasons it pass only empty object to bag array - so that’s the main issue.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.