关于vue.js:🚀vue3封装一个符合思维简单实用的弹出层

前言

在平时开发中,弹出层算是一个最罕用的组件了,尤其是后盾的表单页,详情页,用户端的各种确认都很适宜应用弹出层组件展现,然而个别组件库提供给咱们的个别还是组件的模式,或者是一个简略的服务。

组件模式的弹出层,在我看来应该是组件库提供给咱们二次封装用的,如果间接其实很不合乎直觉

  • 写在页面构造里,然而却不是在页面构造中展现,放在那个地位都不适合只能放在最下边
  • 一个页面如果只有一个弹出层还好保护,多几个先不说放在那里,光保护弹出层的展现暗藏变量都是件头大的事件
  • 弹出层两头展现的如果是一个表单或者一个业务很重的页面,逻辑就会跟页面混在一起不好保护,如果抽离成组件,在后盾这种全是表格表单的时候,都抽离成组件太过麻烦

那么有没有更合乎思维的形式应用弹窗呢,嘿嘿还真有,那就是服务创立弹出层

服务式弹出层

等等!如果是服务创立弹出层每个ui组件库根本都提供了,为什么还要封装呢?因为组件库提供的服务个别都是用于简略的确认弹窗,如果是更重的表单弹窗就难以用组件库提供的服务创立了,咱们以ant-design-vue的modal为例子看看。

<template> 
    <a-button @click="showConfirm">Confirm</a-button>
</template>
<script lang="ts">
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { createVNode, defineComponent } from 'vue';
import { Modal } from 'ant-design-vue';

export default defineComponent({ 
    setup() {
     const showConfirm = () => { 
       Modal.confirm({ 
          title: 'Do you want to delete these items?',
          icon: createVNode(ExclamationCircleOutlined),
          content: 'When clicked the OK button, this dialog will be closed after 1 second', 
          onOk() { 
            return new Promise((resolve, reject) => { 
              setTimeout(Math.random() > 0.5 ? resolve : reject, 1000); 
             }).catch(() => console.log('Oops errors!')); }, 
              // eslint-disable-next-line @typescript-eslint/no-empty-function 
          onCancel() {},
        });
       }; 
     return { showConfirm, };
     },
    }); 
</script>

能够看到modal提供了属性content,在文档里咱们能够看到他的类型是能够传vue组件,然而这样写是有弊病的,咱们无奈在content中的组件敞开modal,想要在子组件敞开Modal须要把Modal自身传递给子组件,而后触发destroy();

显然modal中是一个表单和重业务的组件时,是很难反对咱们的工作的,一是没法简略间接的在子组件敞开弹出层,二是content中的组件传递值给父组件应用也比拟麻烦。

用Promise来创立吧!

promise来创立,咱们通过在close时触发resolve,还能够通过resolve传值,来触发then,这样十分合乎逻辑和语意。
事不宜迟咱们以element-plusdialog为例子,来看看如何用Promise封装弹出层。

// useDialog.ts
import {
  createApp,
  createVNode,
  defineComponent,
  h,
  ref,
  onUnmounted,
} from "vue";

import { ElDialog } from "element-plus";

import type { App, Component, ComputedOptions, MethodOptions } from "vue";
//引入dialog的类型
import type { DialogProps } from "element-plus";

export type OverlayType = {
  component: Component<any, any, any, ComputedOptions, MethodOptions>;
  options?: Partial<DialogProps>;
  params?: any;
};

export class OverlayService {
  //overlay的vue实例
  private OverlayInstance!: App;
  
  // ui库的组件个别都带有动画成果,所以须要保护一个布尔值,来做展现暗藏
  public show = ref<boolean>(false);

  // 组件库的options
  private options: Partial<DialogProps> = {};

  //在open中传递给子组件的参数
  private params: any = {};

  //挂载的dom
  public overlayElement!: Element | null;

  //子组件
  private childrenComponent!: Component<
    any,
    any,
    any,
    ComputedOptions,
    MethodOptions
  >;

  //close触发的resolve,先由open创立赋予
  private _resolve: (value?: unknown) => void = () => {};

  private _reject: (reason?: any) => void = () => {};

  constructor() {
    this.overlayElement = document.createElement("div");
    document.body.appendChild(this.overlayElement);
    onUnmounted(() => {
      //来到页面时卸载overlay vue实例
      this.OverlayInstance?.unmount();
      if (this.overlayElement?.parentNode) {
        this.overlayElement.parentNode.removeChild(this.overlayElement);
      }
      this.overlayElement = null;
    });
  }
 
  private createdOverlay() {
    const vm = defineComponent(() => {
      return () =>
        h(
          ElDialog,
          {
            //默认在弹窗敞开时销毁子组件
            destroyOnClose: true,
            ...this.options,
            modelValue: this.show.value,
            onClose: this.close.bind(this),
          },
          {
            default: () =>
              createVNode(this.childrenComponent, {
                close: this.close.bind(this),
                params: this.params,
              }),
          }
        );
    });
    if (this.overlayElement) {
      this.OverlayInstance = createApp(vm);
      this.OverlayInstance.mount(this.overlayElement);
    }
  }
  //关上弹窗的办法 返回promsie
  public open(overlay: OverlayType) {
    const { component, params, options } = overlay;
    this.childrenComponent = component;
    this.params = params;
    if (options) {
      this.options = options;
    }
    return new Promise((resolve, reject) => {
      this._resolve = resolve;
      this._reject = reject;
      //判断是否有overlay 实例
      if (!this.OverlayInstance) {
        this.createdOverlay();
      }
      this.show.value = true;
    });
  }

  //弹窗的敞开办法,能够传参触发open的promise下一步
  public close(msg?: any) {
    if (!this.overlayElement) return;
    this.show.value = false;
    if (msg) {
      this._resolve(msg);
    } else {
      this._resolve();
    }
  }
}

//创立一个hooks 好在setup中应用
export const useDialog = () => {
  const overlayService = new OverlayService();
  return {
    open: overlayService.open.bind(overlayService),
    close: overlayService.close.bind(overlayService),
  };
};

封装好dialog服务之后,当初咱们先创立一个子组件,传递给open的子组件会承受到close,params两个props

<!--ChildDemo.vue -->
<template>
  <div>
   {{params}}
   
   <button @click="close('敞开了弹窗')" >敞开弹窗</button>
  </div>
</template>
<script lang="ts" setup>
const props = defineProps<{
  close: (msg?: any) => void;
  params: any;
}>();
</script>

而后咱们在页面应用open

<template>
  <div>
   <button @click="openDemo" >关上弹窗</button>
  </div>
</template>
<script lang="ts" setup>
import ChildDemo from './ChildDemo.vue' 
import { useDialog } from "./useDialog";

const { open } = useDialog();

const openDemo = () => {
  open({
    component: ChildDemo,
    options: { title: "弹窗demo" },
    params:{abc:'1'}
  }).then((msg)=>{
    console.log('敞开弹窗触发',msg)
  });
};
</script>

好了到此咱们就封装了一个简略实用的弹窗服务。

写在后头

其实这样封装的还是有一个小问题,那就是没法拿到vue实例,只能拿到overlay的实例,因为overlay是从新创立的vue实例,所以不要应用全局注册的组件,在子组件上独自引入,pinia,vuex,router这些当params做传入子组件。
如果不想本人封装,能够用我写的库vdi useOverlay hook搭配任意的ui组件库,vdi还提供了更好的依赖注入

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理