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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM