Vue2 Modal组件函数式调用封装(基于Ant Design Vue 组件)

发布时间 2023-09-15 14:39:17作者: Better-HTQ

一、h函数(createElement函数)版本

import Vue from "vue";
import { Modal } from "ant-design-vue";

// 获取扩展 Modal 组件
function getModalConstructor(modalProps, childConfig) {
  const { component, ...restConfig } = childConfig;
  return Vue.extend({
    // 添加模态框内的内容
    render(h) {
      return h(
        Modal,
        {
          props: {
            visible: true, // 控制模态框显示
            footer: null, // 底部内容
            // 其他 Modal props
            ...modalProps,
          },
          on: {
            // 监听取消事件
            cancel: () => {
              this.$destroy(); // 销毁实例
            },
          },
        },
        [
          // 在模态框中添加子组件
          h(component, {
            props: {
              ...restConfig.props,
            },
            on: {
              // 子组件内部可通过调用 this.$emit("closeModal"),关闭Modal
              closeModal: () => {
                this.$destroy();
              },
              ...restConfig.on,
            },
          }),
        ]
      );
    },
  });
}

export default function createModal(modalProps, childConfig) {
  const ModalConstructor = getModalConstructor(modalProps, childConfig);
  const instance = new ModalConstructor().$mount();
  document.body.appendChild(instance.$el);
}

二、JSX版本

import Vue from "vue";
import { Modal } from "ant-design-vue";

// 获取扩展 Modal 组件
function getModalConstructor(modalProps, childConfig) {
  const { component, ...restConfig } = childConfig;
  console.log(component, restConfig);
  return Vue.extend({
    // 添加模态框内的内容
    render() {
      const modalConfig = {
        props: {
          visible: true, // 控制模态框显示
          footer: null, // 底部内容
          // 其他 Modal props
          ...modalProps,
        },
        on: {
          // 监听取消事件
          cancel: () => {
            this.$destroy(); // 销毁实例
          },
        },
      };
      const childConfig = {
        props: {
          ...restConfig.props,
        },
        on: {
          // 子组件内部可通过调用 this.$emit("closeModal"),关闭Modal
          closeModal: () => {
            this.$destroy();
          },
          ...restConfig.on,
        },
      };
      return (
        <Modal {...modalConfig}>
          <component {...childConfig} />
        </Modal>
      );
    },
  });
}

export default function createModal(modalProps, childConfig) {
  const ModalConstructor = getModalConstructor(modalProps, childConfig);
  const instance = new ModalConstructor().$mount();
  document.body.appendChild(instance.$el);
}