Vue 3 组合式函数怎么实现全局通知弹窗的状态管理

浅芳吖_7782

浅芳吖_7782

2026-11-04

752人浏览

原创

Vue 3 全局通知弹窗通过模块级 reactive 队列实现状态共享,useNotification 返回统一增删清操作,配合 Teleport 渲染到 body,所有组件调用共享同一响应式数组,无需实例依赖,轻量解耦可扩展。

vue 3 组合式函数怎么实现全局通知弹窗的状态管理

Vue 3 组合式函数实现全局通知弹窗的状态管理,核心在于模块级响应式状态 + 统一调度逻辑 + Teleport 渲染隔离。它不是靠组件实例维护状态,而是利用模块作用域缓存一个共享的响应式通知队列,所有调用方共用同一份数据源。

用组合式函数管理通知队列

定义一个 useNotification 组合式函数(如 composables/useNotification.ts):

  • 在模块顶层创建响应式状态,不依赖任何组件:
    import { ref, reactive, onUnmounted } from 'vue'

// 模块级单例:所有组件共享同一队列 const notifications = reactive([])

// 生成唯一 ID(可选) let idCounter = 0

export interface NotificationItem { id: number title?: string message: string type?: 'success' | 'warning' | 'error' | 'info' duration?: number // 0 表示常驻 onClose?: () => void }

export function useNotification() { const add = (item: Omit) => { const id = ++idCounter const notification = { ...item, id } notifications.push(notification)

// 自动关闭逻辑(若 duration > 0)
if (item.duration && item.duration > 0) {
  setTimeout(() => {
    remove(id)
  }, item.duration)
}

}

const remove = (id: number) => { const index = notifications.findIndex(n => n.id === id) if (index !== -1) { const notification = notifications[index] notification.onClose?.() notifications.splice(index, 1) } }

const clearAll = () => { notifications.forEach(n => n.onClose?.()) notifications.length = 0 }

return { notifications, // 响应式数组,可直接 v-for 渲染 add, remove, clearAll } }

> ✅ 关键点:`notifications` 是模块内 `reactive` 创建的,首次导入即初始化,后续所有组件调用 `useNotification()` 都返回对**同一个数组的引用**,状态天然全局共享。

### 在根组件中集中渲染(配合 Teleport)

创建一个全局通知容器组件 `NotificationPortal.vue`:

```vue
<template><teleport to="body"><div class="notification-portal">
      <notificationitem v-for="n in notifications" :key="n.id" :notification="n"></notificationitem>
</div>
  </teleport></template><script setup lang="ts">
import { useNotification } from '@/composables/useNotification'
import NotificationItem from './NotificationItem.vue'

const { notifications, remove } = useNotification()
</script><style scoped>
.notification-portal {
  position: fixed;
  top: 16px;
  right: 16px;
  z-index: 9999;
  width: 320px;
  max-height: 80vh;
  overflow-y: auto;
}
</style>

再在 App.vue 或 main.ts 中挂载它(只需一次):

Element Plus UI Vue3
Element Plus UI Vue3

Element Plus Vue3 桌面组件库。在开发 Vue 3.x 页面时调用,使用 Element Plus 组件(如 el-button、el-input、el-form、el-table 等)。

下载
<template><router-view></router-view><notificationportal></notificationportal></template>

全局调用: anywhere, anytime

任意业务组件中,无需引入组件、无需 v-if 控制,直接触发:

<script setup lang="ts">
import { useNotification } from '@/composables/useNotification'

const { add } = useNotification()

const handleClick = () => {
  add({
    message: '订单提交成功',
    type: 'success',
    duration: 3000,
    onClose: () => console.log('已自动关闭')
  })
}
</script><template><button>提交</button>
</template>

补充说明

  • 不会重复初始化状态:每次调用 useNotification() 只是读取和操作模块内已存在的 notifications,不是新建响应式对象。
  • 支持异步/动态内容:可在 add() 中传入 onClose、onClick 等回调,或结合 h() 渲染自定义 vnode(如带按钮的通知)。
  • 跨端兼容性好:不依赖特定 UI 库,适配 uniapp、H5、小程序(需注意 Teleport to="body" 在小程序中需替换为 to="#root" 或使用 uni.createSelectorQuery 动态挂载)。
  • 可扩展性强:支持添加队列优先级、去重逻辑、最大显示数量限制(如 notifications.length > 3 && notifications.shift())等。

本质上,这就是 Vue 3 “组合式函数即状态服务”的典型落地——轻量、解耦、可测试、无副作用。

前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!

相关文章

PHP速学视频免费教程(入门到精通)
PHP速学视频免费教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

vue.js vue vue 3

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
python是前端还是后端
python是前端还是后端

Python属于前端也属于后端,其灵活性和丰富的生态系统使得开发人员能够在不同的领域中灵活运用。本专题为大家提供python相关的文章、下载、课程内容,供大家免费下载体验。

2023.08.11

2823

5

前端如何实现即时通讯
前端如何实现即时通讯

实现即时通讯的方法有WebSocket、Long Polling、Server-Sent Events、WebRTC等等。详细介绍:1、WebSocket,它可以在客户端和服务器之间建立持久连接,实现实时的双向通信,前端可以使用 WebSocket API来创建WebSocket连接,并通过发送和接收消息来实现即时通讯;2、Long Polling,是一种模拟实时通信的技术等等。

2023.10.09

6123

6

前端和后端的区别
前端和后端的区别

前端关注的是用户界面的设计和交互,而后端则注重数据处理和逻辑控制。想了解更多前端后端的相关内容,可以阅读本专题下面的文章。

2024.03.19

7050

13

php和前端的关联介绍
php和前端的关联介绍

php既可以作为前端语言,也可以作为后端语言。想了解更多php和前端的相关内容,可以阅读本专题下面的文章。

2024.03.22

6858

10

前端外包工作内容有哪些
前端外包工作内容有哪些

前端外包工作内容包括:1. 网站和应用程序开发;2. 用户界面和交互设计;3. 用户体验优化;4. 设计和视觉开发;5. 跨浏览器兼容性;6. 性能优化;7. 维护和更新;8. 项目管理和沟通。想了解更多前端的相关内容,可以阅读本专题下面的文章。

2024.05.22

983

5

vue2.0和3.0区别
vue2.0和3.0区别

vue2.0和3.0区别:vue2的响应式原理是利⽤“Object.defineProperty()”对数据进⾏劫持结合发布订阅模式的⽅式来实现,vue3中使⽤了es6的proxy API对数据代理,实现对数据的监控。本专题为大家提供vue2.0和3.0区别的相关的文章、下载、课程内容,供大家免费下载体验。

2023.07.17

1734

5

vue3的生命周期有哪些
vue3的生命周期有哪些

vue3的生命周期:1、beforecreate;2、created;3、beforemount;4、mounted;5、beforeupdate;6、updated;7、beforedestroy;8、destroyed;9、activated;10、deactivated等等。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

2024.02.23

12442

5

Vue3组合式API与组件开发实战
Vue3组合式API与组件开发实战

本专题讲解 Vue 3 组合式 API 的核心概念与应用技巧,深入分析响应式系统、生命周期管理、组件设计与复用策略。通过完整项目案例,指导前端开发者实现高性能、结构清晰的 Vue 应用,提升开发效率与代码可维护性。

2026.02.10

336

23

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Vue 教程
Vue 教程

共42课时 | 17.4万人学习

国外Web开发全栈课程全集
国外Web开发全栈课程全集

共12课时 | 1.4万人学习

Vue.js 微实战--十天技能课堂
Vue.js 微实战--十天技能课堂

共18课时 | 1.7万人学习