我需要当用户单击子组件上的按钮时,父组件接收 cart.lenght
以分配元素的 count
属性。
子组件代码
<q-btn flat round color="faded" icon="fas fa-shopping-cart" @click="cart(item.id)"/>
cart: function (Id) {
let cart = []
cart.push(Id)
this.$emit('totalItensCart')
this.$q.localStorage.set('cart', cart)
}
如何在父组件的 count
属性中显示 cart.length
值?
父组件代码
<q-route-tab
count="5"
icon="fas fa-cart-plus"
to="/cart"
exact
slot="title"/>
最佳答案
根据 vue event documentation ,我们想从子组件向父组件发出一个事件。 this.$emit
方法是正确的,但它可以采用两个参数来传递数据,如下所示:
this.$emit("name", data);
因此,让我们从第一个 child 发出购物车中的商品数量:
this.$emit("cartUpdate", cart.length);
现在我们需要在父类中处理这个。我们首先需要一个 data
属性来跟踪 parent 中的 totalCartItems
:
data: function () {
return {
totalCartItems: null
}
}
假设您的两个代码片段都在相同父级的不同子级中,并且第一个子级(发出cartUpdate
) 具有组件名称 first-child
:
<first-child @cartUpdate="cartUpdate"></first-child>
每当子组件发出名为 cartUpdate
的事件(使用 @
shorthand for v-on
)时,这将调用父组件中的 cartUpdate()
方法。方法很简单,只更新parent中的totalCartItems
数据属性:
cartUpdate: function (totalCartItems) {
this.totalCartItems = totalCartItems;
}
最后,让我们通过将它绑定(bind)到数据值来确保它在第二个子组件中得到更新:
<q-route-tab
:count="totalCartItems"
icon="fas fa-cart-plus"
to="/cart"
exact
slot="title"/>
关于vue.js - 子事件发生后立即通知父组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51387328/