Vue3中子组件表单使用v-model给父组件传值
作者:互联网
步骤1:在子组件的props中定义modelValue
步骤2:为表单绑定事件并在更新值的时候发送自定义事件 context.emit('update:modelValue, value)
步骤3:在标签中使用v-model
具体实现
<!-- 子组件模板 -->
<input type="text" :value="inputRef" @input="updateValue" />
export default defineComponent({ props: { modelValue: String }, setup (props, context) {const inputRef = reactive({ val: props.modelValue || '' })
const updateValue = (e:KeyboardEvent) => { const targetValue = (e.target as HTMLInputElement).value inputRef.val = targetValue context.emit('update:modelValue', targetValue) } } )}
<!-- 父组件 --> <template> <div> <input-component v-model="valFromChild"><input-component> <span>{{valFromChild}}<span> <div>
标签:const,Vue3,context,props,组件,targetValue,model,modelValue 来源: https://www.cnblogs.com/MaX666999/p/15965976.html