如何二次封装组件(vue3版本)

831 阅读2分钟

在开发 Vue 项目中我们一般使用第三方组件库进行开发,如 Element-Plus, 但是这些组件库提供的组件并不一定满足我们的需求,这时我们可以通过对组件库的组件进行二次封装,来满足我们特殊的需求。

对于封装组件有一个大原则就是我们应该尽量保持原有组件的接口,除了我们需要封装的功能外,我们不应该改变原有组件的接口,即保持原有组件提供的接口(属性、方法、事件、插槽)不变。

这里我们对 Element-plus 的 input 组件进行简单的二次封装,封装一个 MyInput 组件

1. 继承第三方组件的 Attributes 属性

使用v-bind="$attrs" (透传就行了)

image-3.png

2. 继承第三方组件的 Event 事件

因为vue2还需要使用listeners,而vue3直接使用用上面的v-bind="$attrs"(在Vue3 中,取消了 listeners这个组件实例的属性,将其事件的监听都整合到了attrs上)

3. 使用第三方组件的 Slots

插槽也是一样的道理,比如 el-input 就有4个 Slot,我们不应该在组件中一个个的去手动添加 <slot name="prefix">,因此需要使用 $slots,使用如下代码即可

<template #[slotName]="slotProps" v-for="(slot, slotName) in $slots" >
    <slot :name="slotName" v-bind="slotProps"></slot>
</template>

4. 使用第三方组件的Methods

有些时候我们想要使用组件的一些方法,比如 el-input 提供10个方法,如何在父组件(也就是封装的组件)中使用这些方法呢?其实可以通过 ref 链式调用,但是这样太麻烦了,代码的可读性差;更好的解决方法:将所有的方法暴露出来,供父组件通过 ref 调用!

image-1.png

const myInputRef = ref()
const expose = {} as any
onMounted(() => { 
    const entries = Object.entries(myInputRef.value)
    for (const [method, fn] of entries) {
        expose[method] = fn
    }
})
defineExpose(expose)

然后在父组件直接绑定ref打印组件实例如下

image-2.png

整体子组件代码的结构如下:

<template>
    <div class="my-input">
        <el-input v-bind="$attrs" ref="myInputRef">
            <template #[slotName]="slotProps" v-for="(slot, slotName) in $slots" >
              <slot :name="slotName" v-bind="slotProps"></slot>
            </template>
        </el-input>
    </div>
</template>
<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'defineProps({
    name: String
})
​
const myInputRef = ref()
const expose = {} as any
onMounted(() => { 
    const entries = Object.entries(myInputRef.value)
    for (const [method, fn] of entries) {
        expose[method] = fn
    }
})
defineExpose(expose)
</script><style lang="scss" scoped></style>

整体父组件代码的结构如下:

<template>
    <div class="row">
         <MyInput :aa="inputSize" :title="userName" placeholder="请输入内容" @focus="focus" @click="click" ref="inputRef"></MyInput>
    </div>
</template><script setup>
import { ref, computed,onMounted } from 'vue'
import MyInput from '../components/MyInput/MyInput.vue';
const inputSize = ref(15)
const userName = ref('我是input')
const inputRef = ref()
const focus = () => {
    console.log('聚焦了');
}
const click = () => {
    console.log('点击了');
}
onMounted(() => { 
    console.log(inputRef.value,"组件的实列")
})
</script><style lang="scss" scoped></style>