vue3 挂载全局组件,函数方式调用

函数方式调用

//组件
import sign from "./Sign.vue";
import { createApp, h } from "vue";
import Vant from "vant";
import { ref } from "vue-demi";

export const openSign = (options: any) => {
//Props参数
  const { Name, success, cancel } = options;
  const div = document.createElement("div");
  document.body.appendChild(div);
  let ShowSign = ref(true);
  /**删除节点 */
  const close = () => {
    //@ts-ignore
    app.unmount(div);
    div.remove();
  };
  /**创建节点 */
  const app = createApp({
    render() {
      return h(sign, {
        Name,
        Show: ShowSign.value,
        onSuccess: success,
        onCancel: cancel,
        "onUpdate:Show": (v: any) => {
          ShowSign.value = v;
          if (!v) {
            close();
          }
        },
      });
    },
  });
  app.use(Vant).mount(div);
};
export default openSign;

调用

import Sign from "../check/components/Sign";
//调用
Sign({Name:"",success(v:any){
//签字成功
},cancel(){
//取消签字
});

改进为Promise对象

import sign from "./Sign.vue";
import { createApp, h } from "vue";
import Vant from "vant";
import { ref } from "vue-demi";

export const openSign = (options: any) => {
  let { Name = "您" } = options;
  const div = document.createElement("div");
  document.body.appendChild(div);
  let ShowSign = ref(true);
  //返回Promise对象
  return new Promise((resolve, reject) => {
    /**删除节点 */
    const close = () => {
      //@ts-ignore
      //卸载挂载
      app.unmount(div);
      //删除节点
      div.remove();
    };
    /**创建节点 */
    const app = createApp({
      render() {
        return h(sign, {
          Name,
          Show: ShowSign.value,
          //then的回调触发
          onSuccess: (d: string) => {  //组件emit()
            resolve(d);
          },
          //catch的回调触发
          onCancel: () => { //组件emit()
            reject();
          },
          "onUpdate:Show": (v: any) => {
            ShowSign.value = v;
            if (!v) {
            //关闭弹窗后卸载删除节点
              close();
            }
          },
        });
      },
    });
    //挂载div
    app.use(Vant).mount(div);
  });
};
export default openSign;

调用

 openSign({
      Name: "",
 }).then((v: any) => {
       //执行success
 }).catch(() => {
      //执行cancel
 });

你可能感兴趣的:(vue,vue.js,javascript,前端)