UI组件的二次封装

188 阅读1分钟

UI组件的二次封装

知识点:

  1. useAttrs透传参数给内部组件。
  2. useSlots获取父组件传递过来的插槽函数。
  3. defineExpose把内部组件方法暴露出来。

案例

父组件

<template>
    <div>
        <h1>UI组件二次封装</h1>
        <MyInput ref="myInputRef" a="1" b="2" c="3" placeholder="请输入内容">
            <template #prepend="scope">
                {{ scope }}  //{ a : 1 }
            </template>
        </MyInput>
    </div>
</template>

<script setup lang="ts">
import { nextTick, ref } from 'vue'
import MyInput from './components/MyInput.vue'

//获取el-input中的事件方法
const myInputRef = ref<InstanceType<typeof MyInput>>()
nextTick(() => {
    myInputRef.value?.element.focus()
})
</script>

子组件

<template>
    <div>
        <el-input ref="inputElRef" v-bind="attrs">
            <template v-for="(_, name) in slots" #[name]>
                <slot :name="name" v-bind="data"></slot>
            </template>
        </el-input>
    </div>
</template>

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

interface Props {
    a: string
}
withDefaults(defineProps<Props>(), {})

// input DOM元素
const inputElRef = ref<InstanceType<any>>();
const attrs = useAttrs() //接收非props定义的参数
const slots = useSlots() //获取父组件传递过来的插槽函数

const data = {a: 1}

// 暴露给父组件的参数和方法(外部需要什么,都可以从这里暴露出去)
defineExpose({
    element: inputElRef,
});
</script>