子事件中发生事件时立即通知父组件?

cur*_*ura 1 vue.js

我需要当用户单击子组件上的按钮时,父组件接收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)
}
Run Code Online (Sandbox Code Playgroud)

如何在父组件cart.length中的 count属性中显示值?

父组件代码

 <q-route-tab
        count="5"
        icon="fas fa-cart-plus"
        to="/cart"
        exact
 slot="title"/>
Run Code Online (Sandbox Code Playgroud)

Sam*_*mes 6

根据vue 事件文档,我们希望从子组件向父组件发出一个事件。您使用该this.$emit方法是正确的,但它可以采用两个参数来传递数据,如下所示:

this.$emit("name", data);
Run Code Online (Sandbox Code Playgroud)

因此,让我们从第一个孩子开始计算购物车中的商品数量:

this.$emit("cartUpdate", cart.length);
Run Code Online (Sandbox Code Playgroud)

现在我们需要在父级中处理这个。我们首先需要一个data属性来保持跟踪totalCartItems

data: function () {
    return {
        totalCartItems: null
    }
}
Run Code Online (Sandbox Code Playgroud)

假设您的两个代码片段都在同一父级的不同子级中,并且第一个子级(发出 的子级)具有组件名称:cartUpdatefirst-child

<first-child @cartUpdate="cartUpdate"></first-child>
Run Code Online (Sandbox Code Playgroud)

cartUpdate()每当子组件发出调用的事件cartUpdate(使用 的@简写v-on)时,这将调用父组件中的方法。方法很简单,只更新totalCartItems父级中的数据属性:

cartUpdate: function (totalCartItems) {
    this.totalCartItems = totalCartItems;
}
Run Code Online (Sandbox Code Playgroud)

最后,让我们通过将它绑定到数据值来确保它在第二个子组件中得到更新:

<q-route-tab
        :count="totalCartItems"
        icon="fas fa-cart-plus"
        to="/cart"
        exact
 slot="title"/>
Run Code Online (Sandbox Code Playgroud)