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修饰符来实现父子组件间的数据双向绑定。