步驟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>