组件的二次封装
不管是多样的组件库还是项目中他人封装的组件,实际项目中往往需要二次封装。
1、完整传递原有组件的属性、事件、插槽
vue2:使用v-bind="$attrs"传递属性,v-on="$listeners"传递事件。
vue3:使用v-bind="$attrs"传递属性+事件
以el-input为例
<el-input v-bind="$attrs">
<!-- 透传所有具名插槽 -->
<template v-for="(_, name) in $slots" #[name]="slotProps">
<slot :name="name" v-bind="slotProps"></slot>
</template>
</el-input>
2、按需改造
//在以上基础上可自行改造,例如添加提示信息
<el-input v-bind="$attrs" >
<!-- 透传所有具名插槽 -->
<template v-for="(_, name) in $slots" #[name]="slotProps">
<slot :name="name" v-bind="slotProps"></slot>
</template>
</el-input>
<div class="input-tips">{{tips}}</div> //添加其他固定内容
<slot></slot> //添加插槽
3、暴漏组件内部属性/方法
如果需要使用到组件内部的一些属性和方法,在二次封装时需要对外暴漏处理
<script setup lang="ts">
import { ref } from 'vue'
import { ElInput } from 'element-plus'
const inputRef = ref<InstanceType<typeof ElInput>>()
//vue3中通过defineExpose对外暴漏属性/方法
//vue2中通过$refs获取组件的原生方法【$refs.封装组件Ref.$refs.原生组件Ref.方法()】
defineExpose({
focus: () => {
inputRef.value?.focus()
},
})
</script>
//组件添加ref标识
<el-input ref="inputRef"></el-input>