news 2026/5/1 9:22:47

vue3 实时通讯 SSE

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
vue3 实时通讯 SSE
/** * 原生 EventSource 轻量封装 * 自动重连 & 任意事件监听 * 支持自定义请求头(通过 URL 参数传递 Authorization) */exportdefaultclassSSE{privateurl:string;privatees:EventSource|null;privateretry:number;privateheaders?:Record<string,string>;constructor(url:string,headers?:Record<string,string>){this.url=urlthis.es=nullthis.retry=3000// 重连间隔 msthis.headers=headersthis.connect()}/* 建立连接 */connect():void{// 如果有 headers,将 Authorization 添加到 URL 中(因为 EventSource 不支持自定义 headers)letfinalUrl=this.url;if(this.headers?.Authorization){consttoken=this.headers.Authorization.replace('Bearer ','');constseparator=this.url.includes('?')?'&':'?';finalUrl=`${this.url}${separator}authorization=${encodeURIComponent(token)}`;}this.es=newEventSource(finalUrl)this.es.addEventListener('open',()=>{console.log('[SSE] connected')})this.es.addEventListener('error',()=>{console.log('[SSE] disconnected, retrying...')this.es?.close()setTimeout(()=>this.connect(),this.retry)})}/** * 订阅任意后端事件 * @param {string} event 事件名(与后端 event:xxx 对应) * @param {Function} cb 回调 (data: any) => {} */subscribe<T=any>(event:string,cb:(data:T)=>void):void{this.es?.addEventListener(event,(e:MessageEvent)=>{try{constdata=JSON.parse(e.data)cb(data)}catch(err){console.error('[SSE] parse error',err)}})}/* 手动关闭连接 */close():void{this.es?.close()console.log('[SSE] closed by client')}}
import{defineStore}from'pinia';// 生成唯一 clientIdfunctiongenerateClientId():string{conststored=localStorage.getItem('sse_client_id');if(stored)returnstored;constnewId=`client_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;localStorage.setItem('sse_client_id',newId);returnnewId;}exportconstuseNotificationStore=defineStore('notification',{state:()=>({sse:null,// ...}),actions:{asyncinitSSE(){if(this.sse)return;constclientId=generateClientId();consttoken=localStorage.getItem('token');if(!token){console.error('[NotificationStore] No token found, cannot init SSE');return;}// 建立 SSE 连接,传递 Authorization 请求头constsseUrl=`xxx/xxx/xx?clientId=${clientId}`;this.sse=newSSE(sseUrl,{Authorization:`${token}`});/* 任务状态事件 */this.sse.subscribe<{code:number;data:any;message:string}>('sse_task_status',(payload)=>{console.log('sse监听-----------------------',payload)if(payload.code!==200)return;// payload.data为实时数据// 取出数据放入store});},// 断开 SSE 连接disconnectSSE(){if(this.sse){this.sse.close();this.sse=null;console.log('[NotificationStore] SSE connection closed');}},},});
// 建立连接notificationStore.initSSE()// 断开连接notificationStore.disconnectSSE()

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/5/1 6:08:21

win11蓝屏dump日志无法定位到具体应用终极解决方案

❤️博客主页&#xff1a; iknow181 &#x1f525;系列专栏&#xff1a; 网络安全、 Python、JavaSE、JavaWeb、CCNP &#x1f389;欢迎大家点赞&#x1f44d;收藏⭐评论✍ 一、出现问题 不知道啥时候开始的&#xff0c;电脑有时莫名蓝屏&#xff0c;好像是去年开始的&#xff…

作者头像 李华
网站建设 2026/5/1 6:02:07

亲测好用!8款一键生成论文工具测评:本科生毕业论文必备

亲测好用&#xff01;8款一键生成论文工具测评&#xff1a;本科生毕业论文必备 2026年学术写作工具测评&#xff1a;为何值得一看&#xff1f; 随着AI技术的不断进步&#xff0c;越来越多的学术写作工具涌现出来&#xff0c;帮助学生和研究者提升效率、优化内容质量。然而&…

作者头像 李华
网站建设 2026/5/1 4:49:07

springboot+vue基于spring的药品销售商城进销存管理系统的设计与实现

目录摘要技术要点开发技术核心代码参考示例1.建立用户稀疏矩阵&#xff0c;用于用户相似度计算【相似度矩阵】2.计算目标用户与其他用户的相似度总结源码文档获取/同行可拿货,招校园代理 &#xff1a;文章底部获取博主联系方式&#xff01;摘要 该系统基于SpringBoot和Vue.js技…

作者头像 李华
网站建设 2026/5/1 1:41:27

springboot+vue社区居民信息流动人口管户籍理及数据分析与可视化系统设计

目录 摘要 开发技术 核心代码参考示例1.建立用户稀疏矩阵&#xff0c;用于用户相似度计算【相似度矩阵】2.计算目标用户与其他用户的相似度总结源码文档获取/同行可拿货,招校园代理 &#xff1a;文章底部获取博主联系方式&#xff01; 摘要 该系统基于SpringBoot后端框架与Vue…

作者头像 李华
网站建设 2026/4/30 10:06:24

openJiuwen 0 基础入门:工作流编排从零到一及深度踩坑指南

openJiuwen 0 基础入门&#xff1a;工作流编排从零到一及深度踩坑指南、 前言&#xff1a;什么是工作流&#xff1f; 在接触 openJiuwen 之前&#xff0c;我对“工作流”&#xff08;Workflow&#xff09;这个概念几乎一无所知。听起来像是企业级系统里的高深术语&#xff0c;…

作者头像 李华