美文网首页
二次封装组件如何暴露子组件的方法

二次封装组件如何暴露子组件的方法

作者: rainy66 | 来源:发表于2024-12-25 19:04 被阅读0次

父组件的代码如下:

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

相关文章

网友评论

      本文标题:二次封装组件如何暴露子组件的方法

      本文链接:https://www.haomeiwen.com/subject/vpluejtx.html