The.sync modifier enables bidirectional communication between parent and child components by combining props and $emit.

<div id="app">
  <div>{{bar}}</div>
  <my-comp :foo.sync="bar"></my-comp>
  <! -- <my-comp :foo="bar" @update:foo="val => bar = val"></my-comp> -->
</div>

<script>
  new Vue({
    el: "#app",
    data: { bar: 0}}); Vue.component("my-comp", {
    template: '< h3 > {{foo}} < / h3 > < div @ click = "increment" > I + 1 < / div >',
    data: function(a) {
      return { copyFoo: this.foo };
    },
    props: ["foo"],
    methods: {
      increment: function(a) {
        this.$emit("update:foo"The + +this.copyFoo); }}});</script>
Copy the code

The child component passes a value to the parent via the “update:foo” event, which the parent receives and assigns to the variable “foo”. The child component then receives the new value when it props “foo”. You have two-way communication.


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

After using.sync, it is simplified to

<my-comp :foo.sync="bar"></my-comp>
Copy the code

As you can see, Sync is a syntactic sugar that simplifies writing parent-child component bidirectional communication.