V – the nature of the model
<! - v - the model of writing -- -- >
<my-component type="text" v-model="value">
<! -->
<my-component type="text"
:value="value"
@input="value = $event.target.value"
>
<! Model: {prop: "value", event: "update"} -->
<my-component type="text"
:value="value"
@update="(val) => value = val"
>
Copy the code
Nature. The sync
<! -- Syntactic sugar. Sync -->
<my-component :value.sync="value" />
<! --> < span style = "box-sizing: border-box! Important;
<my-component
:value="msg"
@update:value="(val) => value = val"
>
Copy the code
Both are essentially the same, there is no difference: “listen for a trigger event” =”(val) => value = val”.
The difference between fine points
1. By default, the V-model corresponds to an input event of a component such as input or Textarea. Replacing this input event in a child component would have the same nature as the.sync modifier. Relatively single, can not have more than one.
// The child component can replace the native input event corresponding to the V-model default with a custom event, but we need to manually emit $emit in the child component
model: {
prop: "value".event: "update"
},
Copy the code
A component can have multiple properties with the.sync modifier, which can “bidirectionally bind multiple” prop “at the same time, unlike the V-Model, which has only one for each component.
Summary function scenarios:
- V-model is more about the final operation result, which is the result of bidirectional binding. It is value, which is a change operation.
For example: input field values, checkbox value lists, tree structure binding ID list (ant Design and Element), etc…
- .sync is for more of a variety of states. It is a transfer of states to each other. It is a status, an update operation.
For example: component loading state, submenus and tree expansion lists (a type of state), internal validation state of a form component, and so on…. image.png
There are exceptions, however, where the v-Model can replace the.sync modifier if the component has only one function, which is to switch state, which is the final value of the operation. Using two different ways of bidirectional binding allows us to quickly understand the structure of a component.