Sync modifier: vue. Sync modifier: vue. Sync modifier: vue. Sync modifier: vue. Sync modifier: vue. Sync modifier: vue. However, in practical applications since the 2.0 release, we have found.sync to be useful, for example in developing reusable component libraries. All we need to do is make it easier to distinguish code that changes the state of a parent component from a child component. Since 2.3.0 we have reintroduced the.sync modifier, but this time it only exists as a compile-time syntactic sugar. It is extended to a V-ON listener that automatically updates the parent component’s properties. Example code is as follows:

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

Will be extended to:

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

When a child component needs to update the value of foo, it needs to explicitly fire an update event:

this.$emit('update:foo', newValue)
Copy the code

At first glance, we use an example (popover closing event) to illustrate how this code works.

<template>
    <div class="details">
        <myComponent :show.sync='valueChild' style="padding: 30px 20px 30px 5px; border:1px solid #ddd; margin-bottom: 10px;"></myComponent>
        <button @click="changeValue">toggle</button>
    </div>
</template>
<script>
import Vue from 'vue'
Vue.component('myComponent', {
      template: ` < div v - if = "show" > < p > default initial value is {{to show}}, so it is according to the < / p > < button @. Click the stop = "closeDiv" > close < / button > < / div > `.props: ['show'].methods: {
        closeDiv() {
          this.$emit('update:show'.false); // Fires the input event and passes in a new value}}})export default{
    data(){
        return{
            valueChild:true,}},methods: {changeValue(){
            this.valueChild = !this.valueChild
        }
    }
}
</script>
Copy the code

Dynamic figure link

The function of the sync modifier is that when a child component changes the value of a prop, the change is also synchronized to the parent component binding. If we don’t want to do.sync and we want to do that popover function, we can also pass the initial value, and then the event listener, which isn’t too complicated to implement. The sync implementation here is just to give you an idea of how it works, and there may be other complex features that can be used with Sync.

This is just a simple example. After reading this, do you think there is an instruction similar to this one, V-Model? Yes, when the V-Model is used on components.

Source: littleTank

Link: https://www.jianshu.com/p/6b062af8cf01