vue3 二次组件封装【透传】

vue3 二次组件封装透传

文章目录

  • [vue3 二次组件封装透传](#vue3 二次组件封装透传)

  • 背景:工作中,一些 ui 库的功能对我们业务中想要的功能并不满足,要进行定制化二次的封装,但是封装的过程中我们只想要改动的定制的地方, 其它的属性、事件、插槽、ref 还是想原封不动的透传给个组件,我们不进行任何改动,下面记录下透传的方法。

属性及事件的透传

  • 基于 el-input 二次封装, $attrs 里面会包含除defineProps定义以外所有额外的属性及事件。
js 复制代码
<template>
  <div class="custome-input" :customAttr="customAttr">
    <el-input v-bind="$attrs"> </el-input>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from "vue";

const props = defineProps({
   customAttr:""
});
</script>

插槽的透传

  • 基于 el-input 二次封装, $slots 里面会包含所有的插槽,插槽实际上就是一个一个函数,我们在封装的组件进行遍历传递,这样就动态透传插槽, 而不是一个一个定义,这样不会出现组件插槽时必穿的现象。
js 复制代码
<template>
  <div class="custome-input" :customAttr="customAttr">
    <el-input v-bind="$attrs">
      <template v-for="(_,name)in $slots" #[name]="scopedData">
        <slot :name="name" v-bind="scopedData"></slot>
      </template>
    </el-input>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from "vue";

const props = defineProps({
  customAttr: "",
});
</script>

ref 的透传

  • 基于 el-input 二次封装
  • vue2 中可以使用:$refs 里面是实例的成员变量,这个并没有直接透传的操作, 需要把需要透传的组件实例给当前封装组件的实例一个成员变量的赋值。
js 复制代码
<script>
export default {
  mounted() {
    for (const key in this.$refs.elInp) {
      this[key] = this.$refs.elInp[key];
    }
  },
};
</script>

-下面是 vue3 中的写法, 完整透传 el-input 封装如下:

js 复制代码
<template>
  <div class="custome-input" :customAttr="customAttr">
    <el-input v-bind="$attrs">
      <template v-for="(_,name)in $slots" #[name]="scopedData">
        <slot :name="name" v-bind="scopedData"></slot>
      </template>
    </el-input>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, defineExpose } from "vue";
import type { InputInstance } from "element-plus";
const props = defineProps({
  customAttr: "",
});

const input = ref<InputInstance>();
const inputMethods = ref({});

onMounted(() => {
  const refMethods = Object.entries(input.value).filter(
    ([_, value]) => value instanceof Function
  );
  refMethods.forEach(([key, value]) => {
    inputMethods.value[key] = value;
  });
});
defineExpose(inputMethods.value);
</script>
  • demo 记录而已。不喜勿喷
相关推荐
清风徐来QCQ33 分钟前
SpringMvC
前端·javascript·vue.js
Swift社区43 分钟前
ArkTS Web 组件里,如何通过 javaScriptProxy 让 JS 同步调用原生方法
开发语言·前端·javascript
TttHhhYy1 小时前
小记,antd design vue的下拉选择框,选项部分不跟着滑动走,固定在屏幕某个部位,来改
前端·vue.js·sql
boooooooom1 小时前
Vue3 宏编译的限制与解决方案:深入理解与实践突破
vue.js
Hi_kenyon1 小时前
快速入门VUE与JS(二)--getter函数(取值器)与setter(存值器)
前端·javascript·vue.js
3秒一个大1 小时前
模块化 CSS:解决样式污染的前端工程化方案
css·vue.js·react.js
全栈前端老曹1 小时前
【前端路由】React Router 权限路由控制 - 登录验证、私有路由封装、高阶组件实现路由守卫
前端·javascript·react.js·前端框架·react-router·前端路由·权限路由
zhuà!2 小时前
uv-picker在页面初始化时,设置初始值无效
前端·javascript·uv
摸鱼的春哥2 小时前
实战:在 Docker (Windows) 中构建集成 yt-dlp 的“满血版” n8n 自动化工作流
前端·javascript·后端
_Rookie._2 小时前
关于迭代协议:可迭代协议和迭代器协议,生成器函数 生成器对象的理解
javascript·python