[Vuejs]-Pass value from a component to the parent instance

2👍

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>

Leave a comment