I have a parent component where I am doing the API call and getting the response. So what I am trying to do is pass this response as a prop to child component in Vue. So here is my parent component and the call:
<button class="btn button col-2" @click="addToCart()">
Add to cart
</button>
addToCart: function () {
let amount = this.itemsCount !== "" ? this.itemsCount : 1;
if(this.variationId != null) {
this.warningMessage = false;
cartHelper.addToCart(this.product.id, this.variationId, amount, (response) => {
this.cartItems = response.data.attributes.items;
});
} else {
this.warningMessage = true;
}
},
So I want to pass this "this.cartItems" to the child component which is:
<template>
<div
class="dropdown-menu cart"
aria-labelledby="triggerId"
>
<div class="inner-cart">
<div v-for="item in cart" :key="item.product.id">
<div class="cart-items">
<div>
<strong>{{ item.product.name }}</strong>
<br/> {{ item.quantity }} x $45
</div>
<div>
<a class="remove" @click.prevent="removeProductFromCart(item.product)">Remove</a>
</div>
</div>
</div>
<hr/>
<div class="cart-items-total">
<span>Total: {{cartTotalPrice}}</span>
<a href="#" @click.prevent="clearCartItems()">Clear Cart</a>
</div>
<hr/>
<router-link :to="{name: 'order'}" class="btn button-secondary">Go To Cart</router-link>
</div>
</div>
</template>
<script>
export default {
computed: {
},
methods: {
}
};
</script>
So I am quite new in vue if you can help me with thi, I would be really glad.
Vue.component('Child', { template: ` <div class=""> <p>{{ childitems }}</p> </div> `, props: ['childitems'] }) new Vue({ el: '#demo', data() { return { items: [] } }, methods: { getItems() { //your API call setTimeout(() => { this.items = [1, 2] }, 2000); } } }) Vue.config.productionTip = false Vue.config.devtools = false
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="demo"> <button @click="getItems">get data</button> <Child v-if="items.length" :childitems="items" /> </div>
You can wait for response, and when you gate this.cartItems
then render your child component with a v-if="this.cartItems.length"
condition
Passing props is quite simple. If cartItems
is what you wan´t to pass as a prop, you can do this:
<my-child-component :cartItems="cartItems"></my-child-component>
In this case you implemented your child as myChildComponent
. You pass cartItems
with :cartItems="cartItems"
to it. In your child you do this:
props: {
cartItems: Object
}
Now you can use it with this.cartItems
in your methods or {{cartItems}}
in your themplate.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.