二次封裝組件如何暴露子組件的方法

父組件的代碼如下:

<template>
  <el-button type="primary" @click="focus">聚焦</el-button>
  <MyInput v-model="msg" ref="myInputRef"></MyInput>
</template>
<script setup lang="ts">
import MyInput from './MyInput.vue'
import { ref } from 'vue'
const myInputRef = ref()

const msg = ref('111')
//點擊聚集也同時可以聚焦到子組件的input框
const focus = () => {
  console.log(MyInput)
  myInputRef.value.focus()
}
</script>

子組件MyInput 的代碼如下:

<template>
  <div>
    hello World
  </div>
  <el-input ref="inputRef" v-bind="$attrs"></el-input>
</template>

<script setup lang="ts">
import { ref } from 'vue'

const inputRef = ref()
</script>

<style scoped>

</style>

如何讓子組件的input中ref的方法暴露出來呢
使用defineExpose的方法暴露子組件的方法
父組件代碼如下:

<template>
  <el-button type="primary" @click="focus">聚焦{{ msg }}</el-button>
  <MyInput v-model="msg" ref="myInputRef">
    <template #prepend>
      <el-button>前置</el-button>
    </template>
    <template #append>
      <el-button>后置</el-button>
    </template>
  </MyInput>
</template>
<script setup lang="ts">
import MyInput from './MyInput.vue'
import { ref } from 'vue'
const myInputRef = ref()

const msg = ref('111')
//點擊聚集也同時可以聚焦到子組件的input框
const focus = () => {
  console.log(MyInput)
  myInputRef.value.focus()
}
</script>

子組件代碼如下:

<template>
  <div>
    hello World
  </div>
  <el-input ref="inputRef" v-bind="$attrs">
    <!-- 插槽  slotProps:插槽的作用域值-->
    <template v-for="(_,slot) in $slots" :key="slot" #[slot]="slotProps">
     <slot :name="slot" :v-bind="slotProps"></slot>
    </template>
  </el-input>
</template>

<script setup lang="ts">
import { ref } from 'vue'

const inputRef = ref()

//采用代理的方法把子組件所有的方法暴露出去
defineExpose(
  new Proxy({}, {
    get(target, key) {
      return inputRef.value?.[key]
    },
    has(target, key) {
      return key in inputRef.value
    }
  })
)

</script>

<style scoped>

</style>
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容