fenghe-auction/app/components/floatingBubble/floating.js

100 lines
2.8 KiB
JavaScript
Raw Normal View History

2025-04-10 07:47:40 +00:00
/**
* 浮动气泡窗口管理模块
* 提供创建和销毁浮动气泡窗口的功能
*/
import { createApp } from 'vue'
import MinWindow from '@/components/floatingBubble/index.vue'
import { createI18n } from 'vue-i18n'
// 全局单例状态管理
let minWindowInstance = null // 组件实例引用
let minWindowApp = null // Vue应用实例
let container = null // DOM容器元素
/**
* 创建并显示浮动气泡窗口
* @param {Object} props - 传递给浮动气泡组件的属性
* @returns {Object|null} 返回组件实例或null服务端渲染时
*/
export const showMinWindow1 = (props = {}) => {
// 服务端渲染时直接返回
if (!process.client) return null
// 如果实例已存在,避免重复创建
if (minWindowInstance) {
return minWindowInstance
}
try {
// 清理可能存在的残留容器
const existingContainer = document.querySelector('.floating-bubble-container')
if (existingContainer) {
document.body.removeChild(existingContainer)
}
// 创建新的容器元素
container = document.createElement('div')
container.className = 'floating-bubble-container'
document.body.appendChild(container)
// 创建Vue应用实例
const app = createApp(MinWindow, props)
// 获取当前 Nuxt 应用的 i18n 配置
const nuxtApp = window?.__nuxt
const i18nConfig = nuxtApp?.$i18n?.options || {
legacy: false,
locale: 'en',
messages: {}
}
// 为独立组件创建 i18n 实例
const i18n = createI18n(i18nConfig)
// 安装 i18n
app.use(i18n)
minWindowApp = app
minWindowInstance = app.mount(container)
return minWindowInstance
} catch (error) {
// 发生错误时确保清理资源
hideMinWindow1()
return null
}
}
/**
* 销毁浮动气泡窗口
* 清理所有相关资源和DOM元素
*/
export const hideMinWindow1 = () => {
if (!minWindowApp && !container) return
try {
// 卸载Vue应用
if (minWindowApp) {
minWindowApp.unmount()
}
// 移除DOM容器
if (container && document.body.contains(container)) {
document.body.removeChild(container)
}
// 清理可能残留的其他容器
const existingContainer = document.querySelector('.floating-bubble-container')
if (existingContainer) {
document.body.removeChild(existingContainer)
}
} catch (error) {
} finally {
// 重置所有状态
minWindowApp = null
minWindowInstance = null
container = null
}
}