[英]How to pass props to sibling and child component in vue
我的代码结构是这样的:
因此,在 Product 组件中,我进行了 API 调用:
<template>
<button class="btn button col-2" @click="addToCart()">
Add to cart
</button>
</template>
<script>
methods:{
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;
}
console.log(this.cartItems)
},
}
</script>
我想要做的是响应(this.cartItems)应该显示在 Cart 组件中。 还有我的导航栏组件:
<template>
<nav class="navbar navbar-expand-lg shadow">
<div class="container navbar-container">
<div class="navbar navbar-profile">
<div class="dropdown">
<button class="btn dropdown-toggle" type="button" id="dropdownCart" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
<i class="fa fa-fw fa-cart-arrow-down"></i>
<span></span>
</button>
<div @click="$event.stopPropagation()">
<CartBox :cartItems="cartItems"/>
</div>
</div>
</div>
</div>
</nav>
</template>
<script>
export default {
props: {
cartItems:Object
},
components: {CartBox},
}
和 CartBox:
<template>
<Cart/>
</template>
<script>
import Cart from '../components/Cart'
export default {
components: {
Cart
}
}
</script>
还有我的购物车组件:
<template>
<div
class="dropdown-menu cart"
aria-labelledby="triggerId"
>
<div class="inner-cart">
<div>
<div class="cart-items">
<div>
<a class="remove">Remove</a>
</div>
</div>
</div>
<hr/>
<div class="cart-items-total">
<span>Total:</span>
<a href="#">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>
我真的很困惑如何将道具传递给兄弟组件,然后传递给子组件,但如果你可以将它传递给 Cart 组件,那真的对我有帮助。
您的请求有两种方法:
1.使用props,提供和注入
在将您的响应传递给父母之后,这可以通过Provide / inject来完成。 基本上,您将从您的 Product 组件向父组件emit
响应,可能就像您的 App.vue 作为 prop myData
,然后您为每个子组件提供它,无论它嵌套在哪里,如下所示:
provide: {
providedData: this.myData
}
您现在可以在任何孩子中使用:
inject: ['providedData']
请注意,此数据仅在您的产品组件收到后才可用。 推荐第二种方法。
2. 使用商店
使用vuex
这样的vuex
比方法 1 复杂一些,但是以后会节省很多时间。 您将在您的 Product 组件中接收您的响应,将其发送到商店,并且可以在您的应用程序的任何位置调用来自该商店的信息状态。 请参阅本文档中的更多信息: Vuex | 入门
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.