4
votes

I am building (as an exercise) a shopping cart in vue.js 2. I have my shop items and order items stored in my vue data array and a button rendered in a for loop for each shop item to add the item to the order (ex. push).

Here is the section of code that houses my list of items from my shop array in my vue data:

<fieldset>
    <legend>Shop</legend>
    <section v-if="shop">
        <article v-for="(item, index) in shop">
            <header><h1>{{ item.title }}</h1></header>
            <p>{{ item.description }}</p>
            <footer>
                <ul>
                    <li>${{item.price}}</li>
                    <!-- find a way to set input name -->
                    <li><label>Quantity <input type="number" name=""></label></li>
                    <li><button v-on:click="addItemToOrder($event)">Add to Order</button></li>
                </ul>
            </footer>
        </article>
    </section>
    <p v-else>No Items to Display</p>
</fieldset>

here is my vue element:

new Vue({
    el: '#my-order',
    data:{
        'shop':[
            {
                'title':'Website Content',
                'description':"Order your Website content by the page. Our search-engine-optimized web content puts you ahead of the competition. 250 words.",
                'price':25,
                'sku':'web001'
            },
            {
                'title':'Blog Post',
                'description':"We write blog posts that position your website as a go-to resource for expert knowlegde.",
                'price':50,
                'sku':'blog001'
            },
            {
                'title':'Twitter Post'
            },
            {
                'title':'Product Description'
            }
        ],
        'customizations':null,
        'order':{
            'items':null,
            'total':null
        },
        'customer':null,
        'payment':null
    },
    methods:{
        addItemToOrder: function(){
          /* Here is where I need to append the item to the cart */
        }
    }
})

How do I pass the item in the for loop to the order (eg: append it to order.items)?

2

2 Answers

5
votes

You just need to pass the item in as a parameter to the function.

v-on:click="addItemToOrder(item)"

Then you can use it your Vue component

addItemToOrder: function(item){
    this.order.items.push(item);
}

Make sure you initialize order.items to an empty array inside your components data so that you can push to it.

'order':{
     'items': [],
     'total': 0
},

In general, it is a good idea to initialize your data to the correct data type if you know what it will be.

1
votes

I realise this is a bit late however in case anyone else happens across this thread...

You need to pass in the event as well as the item

in your vue code

someMethod : function(e, item){}

in your html

<a v-on:click="someMethod($event, $data)"></a>