簡單三步在vue3中實現(xiàn)全局js調(diào)用彈窗組件(親測可用)
前言
vue2中我們使用extend方式可以封裝一個全局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)用了?。。。?/p>
總結(jié)
到此這篇關(guān)于在vue3中實現(xiàn)全局js調(diào)用彈窗組件的文章就介紹到這了,更多相關(guān)vue3全局js調(diào)用彈窗組件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue3使用ref與reactive創(chuàng)建響應(yīng)式對象的示例代碼
這篇文章主要詳細(xì)介紹了Vue3使用ref與reactive創(chuàng)建響應(yīng)式對象的方法步驟,文中通過代碼示例和圖文結(jié)合的方式給大家介紹的非常詳細(xì),具有一定的參考價值,需要的朋友可以參考下2024-02-02