当前位置: 首页 > news >正文

组件库二次封装——透传问题

属性和事件透传

属性和事件的透传需要借助一个内置 api $attrs

<my-input a="1" b="2" @change="() => {}" />
<template><div class="input-wrapper">输入框:<el-input v-bind="$attrs"></el-input></div>
</template><script lang="ts">
export default {mounted() {console.log("attrs", this.$attrs)}
}
</script>

在这里插入图片描述

但是这样直接使用 $attrs 透传的优先级会比组件自身的属性和事件优先级低。比如:

<template><div class="input-wrapper">输入框:<el-input v-bind="$attrs"></el-input></div>
</template><script lang="ts">
export default {props: ['a'],emits: ['change'],mounted() {console.log("attrs", this.$attrs)}
}
</script>

在这里插入图片描述

插槽透传

一般我们需要透传插槽的话,需要:

  <my-input v-model="text" ><template #prepend>prepend</template><template #append>append</template><template #suffix>suffix</template><template #prefix>prefix</template></my-input>
<template><div class="input-wrapper">输入框:<el-input v-bind="$attrs"><template #prepend><slot name="prepend"></slot></template><template #append><slot name="append"></slot></template><template #suffix><slot name="suffix"></slot></template><template #prefix><slot name="prefix"></slot></template></el-input></div>
</template>

在这里插入图片描述

这样写有一些问题,一是繁琐,二是可能传递的插槽个数不同,导致不同的渲染逻辑(业务要求)。所以我们需要使用 $slots 这个 api。

插槽的本质是一个函数。

  <my-input v-model="text" ><template #prepend>prepend</template><template #append>append</template></my-input>
<template><div class="input-wrapper">输入框:<el-input v-bind="$attrs"><template v-for="(_, name) in $slots" #[name]="scopedData"><slot :name="name" v-bind="scopedData"/></template></el-input></div>
</template><script lang="ts">
export default {mounted() {console.log("slots", this.$slots)}
}
</script>

在这里插入图片描述

ref 透传

在 vue 中 ref 是无法透传的,在 react 中可以通过 forwardRef 获取子组件。

所以我们只能将子组件内部的原组件库 ref 挂载到外部 二次封装的组件 ref 上。

<template><div class="input-wrapper">输入框:<el-input ref="elInput" v-bind="$attrs"><template v-for="(_, name) in $slots" #[name]="scopedData"><slot :name="name" v-bind="scopedData"/></template></el-input></div>
</template><script>
export default {mounted() {console.log("elInput", this.$refs.elInput)for (const elInputKey in this.$refs.elInput) {this[elInputKey] = this.$refs.elInput[elInputKey];}}
}
</script>

相关文章:

  • 项目练习:Vue2中el-button上的@click事件失效
  • spring4第6课-bean之间的关系+bean的作用范围
  • 解决IDE编译JAVA项目时出现的OOM异常问题
  • DeepSwiftSeek 开源软件 |用于 DeepSeek LLM 模型的 Swift 客户端 |轻量级和高效的 DeepSeek 核心功能通信
  • 《复制粘贴的奇迹:小明的原型工厂》
  • Python训练营打卡DAY44
  • JavaScript性能优化实战技术
  • 全志A40i android7.1 调试信息打印串口由uart0改为uart3
  • leetcode刷题日记——二叉树的锯齿形层序遍历
  • 为UE5的Actor添加能够读写姿态的功能
  • stm32——UART和USART
  • 开源模型应用落地-OpenAI Agents SDK-集成Qwen3-8B-function_tool(二)
  • AI在网络安全领域的应用现状和实践
  • 虚拟机无法开启-关掉虚拟化
  • Java直接内存(directMemory)分配与查看
  • 腾讯位置商业授权AOI边界查询开发指南
  • Web攻防-SQL注入高权限判定跨库查询文件读写DNS带外SecurePriv开关绕过
  • 【Windows开发】Windows 事件跟踪 (ETW)
  • idea相关功能
  • leetcode删除排序链表中的重复元素-小白初学简单解说
  • 西安网站建设哪家公司好/google谷歌搜索
  • 数据网站怎么做的/nba最新新闻
  • 网站的产品图片怎样做清晰/视频号推广
  • 口碑好的天津网站建设/百度网站ip地址
  • 南康家具网站建设/网络推广团队
  • 北京主页网站建设/个人代运营一般怎么收费