![](/img/trans.png)
[英]Is it possible to pass a component as props and use it in a child Component in Vue?
[英]How to pass props to child component in vue
我有一個父組件,我在其中進行 API 調用並獲取響應。 所以我要做的就是將此響應作為道具傳遞給 Vue 中的子組件。 所以這是我的父組件和調用:
<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;
}
},
所以我想將此“this.cartItems”傳遞給子組件,即:
<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>
因此,如果您能幫助我解決這個問題,我對 vue 還是很陌生,我會非常高興。
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>
您可以等待響應,當您this.cartItems
時,然后使用v-if="this.cartItems.length"
條件渲染您的子組件
傳遞道具非常簡單。 如果您不想將cartItems
作為道具傳遞,您可以這樣做:
<my-child-component :cartItems="cartItems"></my-child-component>
在這種情況下,您將孩子實現為myChildComponent
。 您將帶有 : cartItems
:cartItems="cartItems"
的 cartItems 傳遞給它。 在你的孩子身上,你這樣做:
props: {
cartItems: Object
}
現在您可以在方法中使用this.cartItems
或在模板中使用{{cartItems}}
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.