簡單三步在vue3中實(shí)現(xiàn)全局js調(diào)用彈窗組件(親測可用)
前言
vue2中我們使用extend方式可以封裝一個(gè)全局js方式調(diào)用的彈窗組件
但是vue3中已經(jīng)摒棄了extend方法,那如何在vue3的架構(gòu)中去封裝這樣的組件呢?
第一步編寫組件模板
在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調(diào)用全局彈窗 import Dialog from './components/dialog/index.js' app.config.globalProperties.$dialog = Dialog
接下來就可以在vue組件中通過js方式調(diào)用了!?。?!
總結(jié)
到此這篇關(guān)于在vue3中實(shí)現(xiàn)全局js調(diào)用彈窗組件的文章就介紹到這了,更多相關(guān)vue3全局js調(diào)用彈窗組件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue3使用ref與reactive創(chuàng)建響應(yīng)式對(duì)象的示例代碼
這篇文章主要詳細(xì)介紹了Vue3使用ref與reactive創(chuàng)建響應(yīng)式對(duì)象的方法步驟,文中通過代碼示例和圖文結(jié)合的方式給大家介紹的非常詳細(xì),具有一定的參考價(jià)值,需要的朋友可以參考下2024-02-02
在Vue當(dāng)中同時(shí)配置多個(gè)路由文件的方法案例代碼
這篇文章主要介紹了在Vue當(dāng)中同時(shí)配置多個(gè)路由文件的方法,包含具體代碼,本文分步驟結(jié)合示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-12-12
vue自定義鍵盤實(shí)現(xiàn)車牌號(hào)的示例代碼
本文主要介紹了vue自定義鍵盤實(shí)現(xiàn)車牌號(hào)的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07

