Vue组件的二次封装(案例)
📅 2026/7/9 13:05:15
👁️ 阅读次数
📝 编程学习
一、不丢失原生组件的能力
不丢失原组件的任何功能,用户使用封装组件时依旧能用所有原 API
1.1 属性
import{ElInput,typeInputProps}from"element-plus"constprops=withDefaults(defineProps<InputProps>(),{inputStyle:()=>[],})2.2 插槽
<el-input><templatev-for="(slotContent, name) in $slots"#[name]="slotData"><!-- 保留原有插槽内容 --><slot:name="name"v-bind="slotData"/></template></el-input>2.3 事件
<!--父组件--><MyInputplaceholder="请输入"v-model="msg"type="text"ref="myInputRef"@input="handleChange"></MyInput><!--子组件--><el-inputv-bind="{ ...$attrs, ...props }"><templatev-for="(slotContent, name) in $slots"#[name]="slotData"><!-- 保留原有插槽内容 --><slot:name="name"v-bind="slotData"/></template></el-input>2.4 返回方法
constvm=getCurrentInstance()functioncurrentRef(instance:any){if(vm){vm.exposed=instance||{}}}二、封装
<!--父组件--> <template> <MyInput placeholder="请输入" v-model="msg" type="text" ref="myInputRef" @input="handleChange"> <template #append="slotData"> <div>{{ slotData }}</div> </template> <el-button @click="handleClear">点击我清除</el-button> </MyInput> </template> <script setup lang="ts"> 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 class="container"> <div>组件二次封装-{{ $attrs }}</div> <component :is="h(ElInput, { ...$attrs, ...props, ref: currentRef }, $slots)"></component> <slot></slot> </div> </template> <script setup lang="ts"> // inheritAttrs: false 是 Vue 组件中的一个配置项,用于控制是否自动将 $attrs 中的属性传递给组件的根元素。 defineOptions({ inheritAttrs: false, }) import { ElInput, type InputProps } from "element-plus" import { getCurrentInstance, h } from "vue" const props = withDefaults(defineProps<InputProps>(), { inputStyle: () => [], }) const vm = getCurrentInstance() function currentRef(instance: any) { if (vm) { vm.exposed = instance || {} } } const emit = defineEmits(["a"]) </script>
编程学习
技术分享
实战经验