2

I need that when a user clicks a button on the child component the parent component receives cart.lenght to be assigned the count property of an element.

Child component code

<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)
}

How do I display the cart.length value in the count property that is in the parent component?

Parent component code

 <q-route-tab
        count="5"
        icon="fas fa-cart-plus"
        to="/cart"
        exact
 slot="title"/>
Community
  • 1
  • 1
cura
  • 1,035
  • 1
  • 17
  • 33

1 Answers1

8

As per the vue event documentation, we want to emit an event from the child component to the parent component. You are correct with the this.$emit method, but it can take two parameters in order to pass data, like so:

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

So, let's emit a count of the number of items in the cart from the first child:

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

Now we need to handle this in the parent. We'll first need a data property to keep track of the totalCartItems in the parent:

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

Assuming that both of your code snippets are in different children of the same parent, and that the first child (the one that emits cartUpdate) has the component name first-child:

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

This will call the cartUpdate() method in the parent component whenever the child emits an event called cartUpdate (using the @ shorthand for v-on). The method is very simple, only updating the totalCartItems data property in the parent:

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

Finally, let's ensure this gets updated in the second child component by binding it to the data value:

<q-route-tab
        :count="totalCartItems"
        icon="fas fa-cart-plus"
        to="/cart"
        exact
 slot="title"/>
tony19
  • 125,647
  • 18
  • 229
  • 307
Sam Holmes
  • 1,594
  • 13
  • 31
  • I have been using the quasar-framework which is based on VueJs, I had to add `` because it was actually a page of mine! I can learn a lot from your post, it was a big help, thank you! – cura Jul 17 '18 at 21:49
  • @Sam Holmes Maybe you can help me. Look at this : https://stackoverflow.com/questions/52285601/how-can-i-add-notification-automatic-after-add-to-cart-in-the-vue-component – moses toh Sep 12 '18 at 06:43