vue组件二次封装的技巧

70 阅读1分钟

1.我们封装组件要解决的三个问题

  • 属性的透传
  • 插槽的配置
  • 方法的暴露

//父组件
<template>
    <div>
        <MyInput ref="inputRef" v-model="msg">
            <template #append>
                <span>@</span>
            </template>
        </MyInput>
    </div>
</template>
<script lang="ts" setup>
const msg = ref("");
const inputRef = ref();
setTimeout(() => {
    inputRef.value.focus();
}, 1000);
</script>

<template>
    <div>
        <div>二次封装input为例子</div>
        <component
        :is="h(ElInput,{...$attrs,...props, ref: changeRef}, $slots)"
        ></component>
    </div>
</template>
<script lang="ts" setup>
import { getCurrentInstance,h} from "vue";
import { ElInput, type InputPros } from "element-plus";
const props = defineProps<Partial<InputPros>>();
const vm = getCurrentInstance();
function changeRef(inputInstance) {
    vm.expose = inputInstance || {}
    vm.exposeProxy = inputInstance || {}
}
</script>