Usage scenarios: In some cases, we may need to “bidirectional bind” a prop.
However, Vue parent-child communication is a one-way data flow, and the child component cannot directly modify the value of the parent component. (Imagine that if a child component can directly modify a value of the parent component, the parent component can also pass the modified value to the other child component, which is obviously unreasonable.)
The original parent component passes values:
This is why we recommend replacing the schema triggering event with update:myPropName.
The parent component:
Get the second argument passed by $emit with $event
<div>{{doc.title}}</div>
<son-1 :title="doc.title" @update:title="doc.title = $event" />
Copy the code
Data () {return {doc:{title:" title "}}},Copy the code
Subcomponent 1:
<button @click="updateTitle">Copy the code
Data (){return {newTitle:" newTitle 1"}}, methods: {updateTitle(){this.$emit("update:title", this.newtitle)}}Copy the code
Clicking Modify Title changes the rendered “title” in the parent component to “New Title 1”.
use.sync
Decorator:
For convenience, we provide an abbreviation for this pattern, the.sync modifier:
The parent component:
<son-2 :title.sync="doc.title" />
Copy the code
Sub-component 2:
<button @click="updateTitle">Copy the code
Data (){return {newTitle:" newTitle 2"}}, methods: {updateTitle(){this.$emit("update:title", this.newtitle)}}Copy the code
Clicking Modify Title changes the rendered “title” in the parent component to “New Title 2”.
Note: V-bind with the.sync modifier cannot be used with expressions (e.g. :title.sync=”doc.title = $event” is not valid). Instead, you can only provide the name of the property you want to bind to, similar to the V-Model.
use.sync
Modifier set to more than oneprop
:
The.sync modifier can also be used with v-bind when setting multiple prop objects simultaneously:
The parent component:
<div>{{doc.title}}</div>
<div>{{doc.name}}</div>
<son-3 v-bind.sync="doc" />
Copy the code
Data () {return {doc: {title: "title," name: "zs"}}},Copy the code
Sub-component 3:
<button @click="update"> </button>Copy the code
Data () {return {newDoc: {newTitle:" newTitle 3", newName:"ls"}}}, methods: { update(){ this.$emit("update:title", this.newDoc.newTitle) this.$emit("update:name", this.newDoc.newName) } },Copy the code
Click modify data to change the rendered “title” in the parent component to “new title 3” and “ZS” to “LS”.