父组件:
<template>
<div class="w-[500px]">
<h1 class="mb-20">父组件</h1>
<MyInput ref="inputRef" v-model="msg">
<template #append>
<div>append</div>
</template>
</MyInput>
</div>
</template>
<script setup lang="ts">
import MyInput from '@/components/MyInput.vue'
import { ref } from 'vue'
const inputRef=ref()
const msg=ref("Hello World")
setTimeout(()=>{
console.log("inputRef.value=>",inputRef.value)
inputRef.value.clear()
},1000)
</script>
<style scoped>
</style>
MyInput子组件
<template>
<div>
<div>二次封装 input 自定义的内容</div>
<component :is="h(ElInput, { ...$attrs, ...props, ref: changRef }, $slots)"></component>
</div>
</template>
<script lang="ts" setup>
import { ElInput, type InputProps } from 'element-plus'
import { getCurrentInstance, h } from 'vue'
const props = defineProps<Partial<InputProps>>()
const vm = getCurrentInstance()
function changRef(inputInstance: any) {
if (vm) {
vm.exposed = inputInstance || {}
vm.exposeProxy = inputInstance || {}
}
}
/**
* 问题:
* 1. 如何让 props 穿透到子组件?
* 2. 如何让插槽内容穿透到子组件?
* 3. 如何将组件的方法暴露给父组件使用?
*/
</script>
<style scoped></style>