组件的二次封装

组件的二次封装

不管是多样的组件库还是项目中他人封装的组件,实际项目中往往需要二次封装。

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>
相关推荐
LinXunFeng5 小时前
Obsidian - 使用 Share Note 分享笔记并自部署
前端·笔记·github
乘风gg9 小时前
为什么AI 时代来临,大部分人吃不到红利
前端·ai编程·claude
恋猫de小郭9 小时前
Android 限制侧载新进展,谷歌联合国内厂商推验证计划
android·前端·flutter
IT_陈寒9 小时前
Redis内存爆了,原来我漏掉了这个致命配置
前端·人工智能·后端
恋猫de小郭9 小时前
解读 Android 17 全新内存限制,有没有“豁免”后门?
android·前端·flutter
Hyyy11 小时前
理解LLM的基本工作原理:预训练、微调、推理的区别
前端
Gatlin11 小时前
前端逆向与反逆向:一场猫鼠游戏的底层逻辑与实战
前端
代码煮茶11 小时前
React 组件封装方法论 —— 以 Todo App 为例
javascript·react.js
Pedantic11 小时前
本地通知(Local Notifications)学习笔记
前端
任沫12 小时前
Agent之Function Call
javascript·人工智能·go