vue3 使用element-plus中的dialog像MessageBox一样可以进行方法调用

前提

需要安装引入element-plus才可以进行调用

npm install element-plus --save

目的

1.简单场景下实现element-plus中的dialog像MessageBox一样可以进行方法调用

2.不需要维护visible变量

3.支持异步和同步加载弹框组件

4.支持Promise回调

代码实现

import { createVNode, createApp } from 'vue'

const createContainer = () => {
  const container = document.createElement('div')
  document.body.appendChild(container)
  return container
}

/**
 * 
 */
  
export const useModal = async ({ component, props }) => {

  if (component.__asyncLoader) {
    component = await component.__asyncLoader()
  }

  return new Promise((resolve, reject) => {
    const instance = createApp({
      render () {
        return createVNode(component, {
          ...props,
          onClosed: () => {
            instance.unmount()
            document.body.removeChild(instance._container)
          },
          resolve,
          reject,
        })
      }
    })

    const container = createContainer()
    instance.mount(container)
  })

}

代码调用

// 调用弹框的组件

<template>
  <div>
    <el-button type="primary"
               @click="handleBtn">Primary
    </el-button>
  </div>
</template>

<script setup>

import { defineAsyncComponent } from 'vue'
import { useModal } from './components'

const handleBtn = async () => {
  const res = await useModal({
    component: defineAsyncComponent(() => import('./comp.vue')),
    props: {
      a: 1,
      b: 2
    }
  })
}

</script>

// 弹框

<template>

  <el-dialog v-model="visibleRef"
             draggable>
    <el-button type="primary"
               @click="handleOk">OK</el-button>
    <el-button type="primary"
               @click="handleCancel">CANCEL</el-button>
  </el-dialog>

</template>

<script setup>
import { defineProps, ref } from 'vue'

let visibleRef = ref(true)

const props = defineProps(['resolve', 'reject', 'a', 'b'])

const handleOk = async () => {
  visibleRef.value = false
  props.resolve(true)
}

const handleCancel = async () => {
  visibleRef.value = false
  props.reject(false)
}

</script>

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值