vue3.0 实现elementPlus的MessageBox(确认框)组件并挂载到全局使用

notarizeBox.vue

<template>
  <div class="notarize-box">
    <div class="notarize-box-main">
      <div class="notarize-box-message">
        {{ message }}
      </div>
      <div class="notarize-box-footer">
        <button class="btn-primary" @click="onConfirm">确认</button>
        <button class="btn-danger" @click="onCancel">取消</button>
      </div>
    </div>
  </div>
</template>

<script setup  lang='ts'>
defineProps({
  title: {
    type: String,
    default: "",
  },
  message: {
    type: String,
    default: "",
  },
  onConfirm: {
    type: Function,
    default: () => {},
  },
  onCancel: {
    type: Function,
    default: () => {},
  },
});
</script>

<style scoped  lang="scss">
.notarize-box {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999999;

  .notarize-box-main {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: #fff;
    border-radius: 4px;
    padding: 10px;
    max-width: 200px;

    .notarize-box-message {
      font-size: 10px;
      margin-bottom: 10px;
    }
    .btn-primary {
      margin-right: 10px;
    }
  }
}
</style>

notarizeBox.js

import {
    createVNode,
    render,
} from 'vue'

import notarizeBox from './index.vue'

const MessageBox = (message, onConfirm, onCancel) => {
    const container = document.createElement('div')
    document.body.appendChild(container)

    const vnode = createVNode(
        notarizeBox, {
            message,
            onConfirm: () => {
                onConfirm()
                handleClose()
            },
            onCancel: () => {
                onCancel()
                handleClose()
            },
        },
    )
    render(vnode, container)

    // 关闭并删除确认框
    function handleClose() {
        render(null, container)
        document.body.removeChild(container)
    }
}

export default MessageBox

使用方法一: 页面使用示例( 使用的页面单独引入js文件 )

import notarizeBox from "notarizeBox.js 路径";

notarizeBox("确定要删除吗?",
    () => {
        console.log('确认按钮点击事件');
    },
    () => {
        console.log('取消按钮点击事件');
    }
);

使用方法二: 挂在到全局使用

main.ts

import notarizeBox from  'notarizeBox.js 文件路径'
app.config.globalProperties.notarizeBox = notarizeBox;

使用页面

import { getCurrentInstance } from "vue";
const { proxy } = getCurrentInstance() as any;

proxy.notarizeBox("确定要删除吗?",
    () => {
        console.log('确认按钮点击事件');
    },
    () => {
        console.log('取消按钮点击事件');
    }
);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Web Erek

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值