【问题标题】:Notify parent component as soon as event occurs in child event?子事件发生时立即通知父组件?
【发布时间】:2018-07-17 17:37:38
【问题描述】:

我需要当用户单击子组件上的按钮时,父组件接收到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.js


    【解决方案1】:

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

    this.$emit("name", data);
    

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

    this.$emit("cartUpdate", cart.length);
    

    现在我们需要在父节点中处理这个问题。我们首先需要一个data 属性来跟踪父级中的totalCartItems

    data: function () {
        return {
            totalCartItems: null
        }
    }
    

    假设您的两个代码 sn-ps 都在 same 父级的 不同 个子级中,并且第一个子级(发出 cartUpdate 的那个)具有组件名称first-child:

    <first-child @cartUpdate="cartUpdate"></first-child>
    

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

    cartUpdate: function (totalCartItems) {
        this.totalCartItems = totalCartItems;
    }
    

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

    <q-route-tab
            :count="totalCartItems"
            icon="fas fa-cart-plus"
            to="/cart"
            exact
     slot="title"/>
    

    【讨论】:

    • 我一直在使用基于VueJs的quasar-framework,我不得不添加&lt;router-view @ cartItensLength = "setCartLength" @ favoriteItensLength = "setFavoriteLength" /&gt;,因为它实际上是我的一个页面!我可以从您的帖子中学到很多东西,这对我很有帮助,谢谢!
    • @Sam Holmes 也许你可以帮助我。看看这个:stackoverflow.com/questions/52285601/…
    猜你喜欢
    • 2018-06-22
    • 1970-01-01
    • 1970-01-01
    • 2019-12-22
    • 2012-05-02
    • 1970-01-01
    • 1970-01-01
    • 2013-11-07
    • 1970-01-01
    相关资源
    最近更新 更多