Suhail Gupta
Suhail Gupta

Reputation: 23266

Pass value from a component to the parent instance

I have a component named cartComponent with a data property cartCount that gets incremented whenever a new item is added to the cart.

I need to use that value to update the value in the template which is not a part of the component. Is this possible?

Here's is the script for my parent Vue instance:

new Vue({
  el: "#cart-app",
  components: {
    cart: cartComponent
  },
  data: {
    searchQuery: '',
    appliedFilters: ['Day 1'],
    purchaseData: json,
    cCount: 0 // CARTCOUNT; NEEDS TO BE UPDATED FROM COMPONENT
  }
});

Upvotes: 0

Views: 45

Answers (1)

thanksd
thanksd

Reputation: 55644

This is the ideal case for using the .sync modifier.

From the documentation:

When a child component mutates a prop that has .sync, the value change will be reflected in the parent


In your case, you could add the .sync modifier to the cCount property being bound in the template (assuming that your component has a cCount property):

<cart :c-count.sync="cCount"></cart>

And in the script for the cart component emit an update:cCount event when the count is incremented:

methods: {
  incrementCount() {
    this.cartCount++;
    this.$emit('update:cCount', this.cartCount);
  }
}

This will automatically set the value of the parent Vue instance's cCount property to the value of the cart component's cartCount property.

Here's a working fiddle.


This feature is available starting in Vue version 2.3.0, but if you are using an earlier version, this would give you the same functionality:

<cart :c-count="cCount" @update:foo="val => cCount = val"></cart>

This is because <comp :foo.sync="bar"></comp> is just syntactic sugar for:

<comp :foo="bar" @update:foo="val => bar = val"></comp>

Upvotes: 2

Related Questions