如何更优雅二次封装ElementUI

一、如何继承Element组件的属性Attributes

1.1. 需要$attrs

$attrs组件实例的该属性包含了父作用域中不作为prop被识别 (且获取) 的 attribute 绑定 (class和style除外)。当一个组件没有声明任何 prop 时,这里会包含所有父作用域的绑定 (class和style除外),并且可以通过v-bind="$attrs"传入内部的 UI 库组件中。

<template>
  <div class="t_select">
    <el-select v-model="childSelectedValue" :style="{ width: width || '100%' }" v-bind="attrs">
      <el-option
        v-for="(item, index) in optionSource"
        :key="index + 'i'"
        :label="item[labelKey]"
        :value="item[valueKey]"
      ></el-option>
    </el-select>
  </div>
</template>
<script>
export default {
  name: "TSelect",
  computed: {
    attrs() {
      return {
        // 'popper-append-to-body': false,
        clearable: true, // 默认开启清空
        filterable: true, // 默认开启过滤
        ...this.$attrs,
      };
    },
  },
};
</script>

二、如何继承Element组件的事件Events

2.1. 需要$listeners

$listeners组件实例的该属性包含了父作用域中的(不含.native修饰器的)v-on事件监听器。它可以通过v-on="$listeners"转发传入内部组件,进行对事件的监听处理。

<template>
  <div class="t_select">
    <el-select
      v-model="childSelectedValue"
      :style="{ width: width || '100%' }"
      v-bind="attrs"
      v-on="$listeners"
    >
      <el-option
        v-for="(item, index) in optionSource"
        :key="index + 'i'"
        :label="item[labelKey]"
        :value="item[valueKey]"
      ></el-option>
    </el-select>
  </div>
</template>

三、如何继承Element组件的方法methods

image.png

  • 我们不应该在组件中一个一个的去手动添加clearSort() { this.$refs['el-table'].clearSort() }

  • 因此需要在组件中根据this.$refs['el-table']来遍历el-table所有的方法将其挂载在我们自己的组件this
    image.png

mounted() {
  this.extendMethod();
},
methods: {
  // 继承el-table的Method
  extendMethod() {
    const refMethod = Object.entries(this.$refs["el-table"]);
    for (const [key, value] of refMethod) {
      if (!(key.includes("$") || key.includes("_"))) {
        this[key] = value;
      }
    }
  },
},

四、如何使用第三方组件的Slots

  • 我们不应该在组件中一个一个的去手动添加<slot name="prefix">
  • 因此需要$slots和$scopedSlots

$slots普通插槽,使用$slots这个变量拿到非作用域的插槽,然后循环渲染对应的普通具名插槽,这样就可以使用第三方组件提供的原插槽;
$scopedSlots作用域插槽则绕了一圈,使用了一个插槽的语法糖(具名插槽的缩写)并且结合着动态插槽名的用法;循环$scopedSlots作用插槽位置和传递对应的参数,,这样就可以使用第三方组件提供的作用域插槽。

<template>
  <div class="t_input">
    <el-input v-model="childSelectedValue" v-bind="attrs" v-on="$listeners">
      <!-- 遍历子组件非作用域插槽,并对父组件暴露 -->
      <template v-for="(index, name) in $slots" v-slot:[name]>
        <slot :name="name" />
      </template>
      <!-- 遍历子组件作用域插槽,并对父组件暴露 -->
      <template v-for="(index, name) in $scopedSlots" v-slot:[name]="data">
        <slot :name="name" v-bind="data"></slot>
      </template>
    </el-input>
  </div>
</template>

五、Vue 3组件封装的变化

5.1. $attrs 与 $listeners 合并

Vue 3.x当中,取消了$listeners这个组件实例的属性,将其事件的监听都整合到了$attrs这个属性上了,因此直接通过v-bind=$attrs属性就可以进行props属性和 event 事件的透传。

5.2. $slot 与 $scopedSlots 合并

Vue 3.x当中取消了作用域插槽$scopedSlots的属性,将所有插槽都统一在$slots当中,因此在 Vue 3.x 当中不需要分默认插槽、具名插槽和作用域插槽,可以进行统一的处理。

5.3. 如何继承第三方组件的Methods

<template>
  <el-form
    class="t-form"
    ref="tform"
    :class="className"
    :model="formOpts.formData"
    :rules="formOpts.rules"
    :label-width="formOpts.labelWidth || '100px'"
    :label-position="formOpts.labelPosition || 'right'"
    v-bind="$attrs"
  >
    ....
  </el-form>
</template>

<script setup lang="ts">
import { ref, onMounted, getCurrentInstance } from "vue";
// 获取ref
const tform: any = ref<HTMLElement | null>(null);
// 获取实例方法
const instance: any = getCurrentInstance();

onMounted(() => {
  // 把el-form方法注入到实例的exposed中
  const entries = Object.entries(tform.value.$.exposed);
  // console.log('111', entries)
  for (const [key, value] of entries) {
    instance.exposed[key] = value;
  }
});
// 自定义校验
const selfValidate = () => {
  return new Promise((resolve: any, reject: any) => {
    tform.value.validate((valid: boolean) => {
      if (valid) {
        resolve({
          valid,
          formData: props.formOpts.formData,
        });
      } else {
        // eslint-disable-next-line prefer-promise-reject-errors
        reject({
          valid,
          formData: null,
        });
      }
    });
  });
};
// 暴露方法出去
defineExpose({ ...instance.exposed, selfValidate });
</script>
  • 7
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值