Vue中的v-model
和.sync
修饰符都是用于实现父子组件间数据双向绑定的机制。尽管它们的作用相似,但在使用方式和实现细节上有所区别。
v-model
v-model
是一个指令,用于在表单类元素上创建双向数据绑定。在Vue3中,v-model
可以在自定义组件上使用,并且可以指定绑定的属性和事件。
父组件
<template>
<div>
<p>父组件中的数据: {{ parentData }}</p>
<ChildComponent v-model="parentData" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
parentData: 'Hello'
};
}
};
</script>
子组件
<template>
<div>
<input :value="modelValue" @input="updateValue" />
</div>
</template>
<script>
export default {
props: {
modelValue: {
type: String,
default: ''
}
},
methods: {
updateValue(event) {
this.$emit('update:modelValue', event.target.value);
}
}
};
</script>
在这个例子中,v-model
在父组件中绑定到parentData
,在子组件中使用modelValue
作为prop接收,并且当输入框内容变化时,触发update:modelValue
事件来更新父组件的数据。
.sync修饰符
.sync
修饰符是Vue2中引入的,用于简化子组件向父组件传递数据的过程。在Vue3中,.sync
可以与v-model
的语法糖一起使用,使得子组件可以同时支持这两种方式的数据传递。
父组件
<template>
<div>
<p>父组件中的数据: {{ parentData }}</p>
<ChildComponent :value.sync="parentData" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
parentData: 'Hello'
};
}
};
</script>
子组件
<template>
<div>
<input :value="value" @input="updateValue" />
</div>
</template>
<script>
export default {
props: {
value: {
type: String,
default: ''
}
},
methods: {
updateValue(event) {
this.$emit('update:value', event.target.value);
}
}
};
</script>
在这个例子中,.sync
修饰符在父组件中绑定到parentData
,在子组件中使用value
作为prop接收,并且当输入框内容变化时,触发update:value
事件来更新父组件的数据。
区别
-
v-model
是一个指令,而.sync
是一个修饰符。 -
v-model
通常用于表单类元素的双向数据绑定,而.sync
可以用于任何prop的双向数据绑定。 -
v-model
在自定义组件上使用时,可以指定绑定的属性和事件,而.sync
只能用于默认的value
属性和input
事件。
在实际开发中,可以根据需要选择使用v-model
或.sync
修饰符来实现父子组件间的数据双向绑定。