简单三步在vue3中实现全局js调用弹窗组件(亲测可用)
作者:GD-Frontender
这篇文章主要介绍了在vue3中实现全局js调用弹窗组件的相关资料,文中通过创建Dialog.vue组件、index.js导出及main.js注册,实现JS调用弹窗功能,需要的朋友可以参考下
前言
vue2中我们使用extend方式可以封装一个全局js方式调用的弹窗组件
但是vue3中已经摒弃了extend方法,那如何在vue3的架构中去封装这样的组件呢?
第一步编写组件模板
在components目录下新建文件夹dialog,在该目录下新建Dialog.vue和index.js文件
Dialog.vue文件:
<template>
<div class="self-dialog">
<el-dialog
v-model="dialogData.show"
:title="dialogData.title"
:close-on-click-modal="false"
:close-on-press-escape="false"
destroy-on-close
:width="dialogData.width"
:before-close="handleClose"
>
<span>{{ dialogData.content }}</span>
<template #footer>
<div class="dialog-footer">
<el-button @click="handleClose">取消</el-button>
<el-button type="primary" @click="handleConfirm">确定</el-button>
</div>
</template>
</el-dialog>
</div>
</template>
<script setup>
import { inject, getCurrentInstance, computed } from 'vue'
const config = inject('config')
const { proxy } = getCurrentInstance()
const dialogData = computed(() => {
let defaultData = {
show: false,
content: '',
width: '800px',
title: '弹窗',
onConfirm: () => {},
onCancel: () => {}
}
return {
...defaultData,
...config
}
})
const handleClose = () => {
dialogData.value.onCancel()
document.body.removeChild(proxy.$el.parentNode)
}
const handleConfirm = () => {
dialogData.value.onConfirm()
document.body.removeChild(proxy.$el.parentNode)
}
</script>index.js文件:
import { createApp } from 'vue'
import dialog from './Dialog.vue'
class Dialog {
constructor() {
this.instance = null
this.mountDom = document.createElement('div')
}
show(options) {
this.instance && this.instance.unmount()
this.instance = createApp(dialog)
this.instance.provide('config', options)
this.instance.mount(this.mountDom)
document.body.appendChild(this.mountDom)
}
hide() {
this.instance && this.instance.unmount()
}
}
export default new Dialog()main.js文件:
// js调用全局弹窗 import Dialog from './components/dialog/index.js' app.config.globalProperties.$dialog = Dialog
接下来就可以在vue组件中通过js方式调用了!!!!
总结
到此这篇关于在vue3中实现全局js调用弹窗组件的文章就介绍到这了,更多相关vue3全局js调用弹窗组件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
