If you're looking for the perfect scenario to utilize the .sync
modifier, this is it.
According to the documentation:
When a prop with .sync is modified by a child component, the changes will be reflected in the parent component
In your specific situation, consider adding the .sync
modifier to the cCount
property that's being bound in the template (assuming that your component includes a cCount
property):
<cart :c-count.sync="cCount"></cart>
Additionally, in the script section of the cart component, emit an update:cCount
event whenever the count is incremented:
methods: {
incrementCount() {
this.cartCount++;
this.$emit('update:cCount', this.cartCount);
}
}
Doing this will automatically adjust the value of the cCount
property in the parent Vue instance to match the value of the cartCount
property within the cart component.
Check out this functional fiddle for reference.
Note that this functionality is supported from Vue version 2.3.0 onwards. However, if you are using an earlier version, you can achieve the same result using the following syntax:
<cart :c-count="cCount" @update:foo="val => cCount = val"></cart>
This is because
<comp :foo.sync="bar"></comp>
is essentially shorthand for:
<comp :foo="bar" @update:foo="val => bar = val"></comp>