The difference between the v-model directive and the.sync modifier in vue:
v-model
<! -- Parent component -->
<template>
<! -- The v-model directive is syntax sugar -->
<Child v-model="model"></Child>
<! The following code is equivalent to the v-model directive -->
<! Prop = value; prop = input; prop = value;
<Child :value="model" @input="model = $event"></Child>
</template>
Copy the code
You can also modify the default event and prop custom properties of the V-Model binding via the Model option in the child component:
/ / child component
export default {
model: {
prop: 'checked'.event: 'change'}}Copy the code
Therefore, the equivalent operation of the corresponding parent component using v-Model is:
<template>
<Child :checked="model" @change="model = $event"></Child>
<template>
Copy the code
V-models are often used for form controls because they give components more control
.sync
<! -- Parent component -->
<template>
<! --.sync was added to V2.4, which can be used to modify properties passed to child components -->
<Child :xxx.sync="model"></Child>
<! -- equivalent to the following code -->
<Child :xxx = "model" @update:xxx = "model = $event"></Child>
</template>
<! -- Subcomponent -->
<input :value="xxx" @input = "$emit('update:xxx', $event.target.value)"/>
Copy the code
Here the binding property name XXX can be changed, as can the corresponding property name:
<! -- Parent component -->
<template>
<Child :foo.sync="model"></Child>
</template>
<! -- Subcomponent -->
<input :value = "foo" @input = "$emit('update:foo', $event.target.value)"/>
Copy the code
The.sync principle uses the $emit method for child components to send events to parent components. The application scenario is that the child component wants to modify the attributes passed by the parent component.
Control of the.sync modifier resides with the parent component, and the event name is relatively fixed update: XXX