Home > Software design >  How to send & receive object as a props in Vue.js
How to send & receive object as a props in Vue.js

Time:11-13

I have a Product object and I am taking it from API call. So in parent component I want to send this object into the child object which is SoldTickets component.

So here is my parent component:

<template>
    <section id="cart-page" >
        <div v-for="item in cart.attributes.items" :key="item.id">
            <div >
                <div >WARENKORB</div>
                <SoldTickets :item = item />
            </div>
        </div>
    </section>
</template>

And my child:

<template>
    <div id="sold-tickets">
        <div >
            <div >
                <div >
                    <div >
                        <div >
                            <div >{{ item.product_name }}</div>
                            <div >{{ item.variation_name }}</div>
                        </div>
                    </div>
                    <DeleteButton @click.prevent="removeProductFromCart(item.id)" />
                </div>
            </div>
        </div>
    </div>
</template>
<script>
export default {
    props: {
        data: {
            item: Object,
        }
    },
}
</script>

So I am quite new in Vue so I am not really confident with props. COuld you please help me with this.

CodePudding user response:

You mostly have it right, but there are a couple of errors:

Your props aren't declared correctly in the child component, you shouldn't have the "data" in there. All props you want to declare go directly under the "props" key of the component declaration:

export default {
    props: {
        item: Object,
    },
}

You're also missing quotes around the attribute value in the parent component, so that's invalid HTML:

<SoldTickets :item = item />

should be

<SoldTickets :item = "item" />

CodePudding user response:

Just wrap the bound value with "" or '' like :

<SoldTickets :item="item" />
  • Related