[Solved] Vue modifier.sync (Avoid mutating a prop directly since …… a solution to the error)

Foreword

We all know that the child component will report an error when modifying the props passed from the parent component, as shown below
Please add image description

1. What is .sync

When we want to modify data across parent-child components, we need parent-child component communication, parent-to-child: bind data in the child component and then the child component receives it with props, and child-to-parent, the parent component needs to bind events on the component, Subcomponents use $emit to pass events; such data modification is a bit troublesome to write. The .sync modifier is an abbreviation for the above subcomponents to modify the parent component data.

The use of .sync

grammar:

:props name .sync=”props value”
$emit(“update:props name”, new value)

parent component

<child-dialog :name.sync="userName"></child-Dialog>

Subcomponent

<el-button type="primary" @click="changeName('Wang Wu')">Change name</el-button>
methods:{<!-- -->
changeName(newName){<!-- -->
//Modify the data passed from the parent component
this.$emit('update:name', newName)
}
}

The :name.sync modifier is actually an abbreviation for the following code
@update:name="val => name=val"

3. Other props two-way binding method

Pass Object

Put the value of the basic data type that needs to be passed into the object, and modify the value in the object in the subcomponent without reporting an error. The principle is that the object is a complex data type, and the object received by the subcomponent and the object passed by the parent component share one memory address, so it can achieve the effect of two-way bonding.
parent component

<div>
<child-dialog :toChildObj="obj"></child-Dialog>
<p>
<span>Name:</span>{<!-- -->{<!-- -->name}}
</p>
</div>
export default {<!-- -->
data(){<!-- -->
return{<!-- -->
obj:{<!-- -->
name: "Zhang San"
}
}
}
}

Subcomponent

<el-button type="primary" @click="changeName('Wang Wu')">Change name</el-button>
export default {<!-- -->
props:{<!-- -->
toChildObj:{<!-- -->
type:Object,
default:{<!-- -->}
},
},
data(){<!-- -->
return{<!-- --> }
},
methods:{<!-- -->
changeName(newName){<!-- -->
//Modify the data passed from the parent component
this.toChildObj.name = newName;
}
}
}