在 React 中渲染远端的 Vue 组件,有其他更好方案吗?

356 阅读1分钟

之前写了一篇文章介绍了低代码加载组件的方式 不安装依赖,直接调用 npm | 远端 React 组件,现在想在React 中直接加载远端的 Vue 组件,目前用的是直接createApp, 更新数据直接使用 vueInstance.current._instance.data

import { isObject } from '@/utils';
import { useEffect, useRef } from 'react';
import { App, Component, createApp, defineComponent, h } from 'vue';

interface VueRenderProps {
  component: Component;
  componentName: string;
  refFn: Function;
  [key: string]: unknown;
}
const VueRender = (props: VueRenderProps) => {
  const { component, componentName, refFn, comEvents, ...otherProps } =
    props;
  const vueInstance = useRef<App<Element>>(null);
  const vueRenderMountElement = useRef<HTMLDivElement>(null);
  useEffect(() => {
    vueInstance.current?.unmount();
    const RootComponent = defineComponent({
      name: componentName + 'Wrapper',
      data: function () {
        return { otherProps: otherProps };
      },
      render() {
        const componentProps = {
          ...this.otherProps,
          ref: (value: unknown) => {
            refFn?.(value);
          },
        };
        if (isObject(comEvents)) {
          for (const eventName in comEvents) {
            componentProps[`on${eventName[0].toLocaleUpperCase()}${eventName.slice(1)}`] =
              comEvents[eventName];
          }
        }
        return h(component, componentProps);
      },
    });
    vueInstance.current = createApp(RootComponent);
    vueInstance.current.mount(vueRenderMountElement.current);
  }, []);

  useEffect(() => {
    vueInstance.current._instance.data.otherProps = otherProps;
  }, [otherProps]);

  return <div ref={vueRenderMountElement}></div>;
};

export default VueRender;