1:作用在表单元素上实际上就是
2:作用在自定义组件上,vue2和vue3不同
vue2:
v-model相当于名为value 的 prop和名为 input 的事件
在父组件中
<child v-model="message"></child>
//相当于:
<child :value="message" @input="function(e){message = e}"></child>
在子组件中
props:['value']
methods:{onmessage(e){$emit('input',e.target.value)}
}
vue3:
v-model默认相当于名为modelValue的 prop和名为 update:modelValue的事件
父组件中:
<child v-model="message"></child>
<child :modelValue="message" @update:modelValue="function(e){message = e}"></child>
在子组件中:
const props = defineProps({modelValue: {type: String}
})
const emit = defineEmits(["update:modelValue",
]);
const onMessage = (e) => {emit('update:modelValue', e.target.value)
}
但是也可以自定义v-model的变量名,例如
父组件中
<Child v-model:childData="childData"><p>默认插槽的内容,孩子2</p>
</Child>
子组件中
<input type="text" :value="childData" @input="onMessage($event)" />
const props = defineProps({childData: {type: String}
})
const emit = defineEmits(["update:childData",
]);
const onMessage = (e) => {emit('update:childData', e.target.value)
}