element-plus 二次封装ref 代理解决方案

130 阅读1分钟

1.新建方法

/** defineExpose代理 */
export function exposeProxy(elProxy: { [property: string]: any }, el: Ref) {
  if (!el) {
    return elProxy;
  }
  return new Proxy(elProxy, {
    get: (target, key: string) => {
      if (el.value && el.value[key]) {
        return el.value[key];
      }
      return target[key];
    },
    set(target, key: string, newValue) {
      if (el.value && el.value[key]) {
        el.value[key] = newValue;
        return true;
      }
      return !!target[key];
    }
  });
}

2.element-plus 二次封装案例

<template>
  <Form v-bind="$attrs" ref="el" :label-width="labelWidth">
    <template v-for="(value, key) in $slots" :key="key" #[key]="scope">
      <slot :name="key" v-bind="scope" :label-width="labelWidth"></slot>
    </template>
  </Form>
</template>
<script setup lang="ts" name="ElForm">
import * as ElementPlus from "element-plus";
import { exposeProxy } from "@/utils/index";
const el = ref();
const elProxy = {
  element: el,
  validate() {},
  validateField() {},
  resetFields() {},
  clearValidate() {},
  scrollToField() {}
};
const $slots: { [property: string]: any } = useSlots();
const Form: any = ElementPlus.ElForm;

defineExpose(exposeProxy(elProxy, el));
</script>