前言
在项目中或许需要做二次封装组件,这里我们用 element plus 做案例,二次封装一个 input,可以对组件进行扩展
方案1
// 使用 $attrs $slots,操作 ref 方法没有找到最合适的
<script setup lang="ts">
import { ElInput } from 'element-plus';
const inputRef = ref();
// 抛出 ref 获取函数
function getRef() {
return inputRef.value;
}
defineExpose({
getRef
});
</script>
<template>
<div>
<el-input ref="inputRef" v-bind="$attrs">
<template v-for="(_, slot) in $slots" :key="slot" #[slot]="slotProps">
<slot :name="slot" v-bind="slotProps"></slot>
</template>
</el-input>
</div>
</template>
方案2,使用 h() 函数
<script setup lang="ts">
import { h } from 'vue';
import { ElInput } from 'element-plus';
const inputRef = ref(null);
defineExpose({
ref: inputRef
});
</script>
<template>
<component :is="h(ElInput, $attrs, $slots)" ref="inputRef"></component>
</template>