Vue组件的二次封装(案例)
一、不丢失原生组件的能力不丢失原组件的任何功能用户使用封装组件时依旧能用所有原 API1.1 属性import{ElInput,typeInputProps}fromelement-plusconstpropswithDefaults(definePropsInputProps(),{inputStyle:()[],})2.2 插槽el-inputtemplatev-for(slotContent, name) in $slots#[name]slotData!-- 保留原有插槽内容 --slot:namenamev-bindslotData//template/el-input2.3 事件!--父组件--MyInputplaceholder请输入v-modelmsgtypetextrefmyInputRefinputhandleChange/MyInput!--子组件--el-inputv-bind{ ...$attrs, ...props }templatev-for(slotContent, name) in $slots#[name]slotData!-- 保留原有插槽内容 --slot:namenamev-bindslotData//template/el-input2.4 返回方法constvmgetCurrentInstance()functioncurrentRef(instance:any){if(vm){vm.exposedinstance||{}}}二、封装!--父组件-- template MyInput placeholder请输入 v-modelmsg typetext refmyInputRef inputhandleChange template #appendslotData div{{ slotData }}/div /template el-button clickhandleClear点击我清除/el-button /MyInput /template script setup langts import { ref } from vue import MyInput from ./components/index.vue const myInputRef ref() const msg ref(1111111111) const handleClear () { if (!myInputRef.value) return myInputRef.value.clear() } const handleChange () { console.log(111) } /script!---子组件-- template div classcontainer div组件二次封装-{{ $attrs }}/div component :ish(ElInput, { ...$attrs, ...props, ref: currentRef }, $slots)/component slot/slot /div /template script setup langts // inheritAttrs: false 是 Vue 组件中的一个配置项用于控制是否自动将 $attrs 中的属性传递给组件的根元素。 defineOptions({ inheritAttrs: false, }) import { ElInput, type InputProps } from element-plus import { getCurrentInstance, h } from vue const props withDefaults(definePropsInputProps(), { inputStyle: () [], }) const vm getCurrentInstance() function currentRef(instance: any) { if (vm) { vm.exposed instance || {} } } const emit defineEmits([a]) /script