uniapp vue2版本使用sse通信 日期:2025-04-08 人气:13 - 定义一个store用来存储消息 ``` const message = { state: { notices: [] }, mutations: { SET_NOTICES: (state, notices) => { state.notices = notices }, ADD_NOTICE: (state, notice) => { state.notices.push(notice) }, REMOVE_NOTICE: (state, notice) => { state.notices.splice(state.notices.indexOf(notice), 1); }, CLEAR_NOTICE: (state) => { state.notices = []; }, READ_ALL: (state) => { state.notices.forEach((item) => { item.read = true; }); } } } export default message ``` - 定义一个初始化sse的方法 ``` import { getToken } from '@/utils/auth'; import modal from '@/plugins/modal' import store from "@/store" import config from '@/config' import { tansParams } from '@/utils/common' // 初始化 export const initSSE = (url) => { if ("EventSource" in window) { url = url + '?' + tansParams({ Authorization: 'Bearer ' + getToken(), clientid: config.VITE_APP_CLIENT_ID }) // 创建EventSource对象并指定SSE服务器的路径 var source = new EventSource(url); // 监听消息的传输 source.onmessage = function(e) { console.log(e) // 对接收到的数据进行处理 if (!e.data) return; store.commit('ADD_NOTICE', { message: e.data, read: false, time: new Date().toLocaleString() }) modal.msg(e.data); // origin = e.origin; uni.showTabBarRedDot({ //显示红点 index: 2 }) }; // 连接建立成功时触发 source.onopen = function(e) { console.log("连接打开."); }; // 连接发生错误时触发 source.onerror = function(e) { if (e.readyState == EventSource.CLOSED) { console.log("连接关闭"); } else { console.log("onerror:" + e.readyState); } }; } else { console.log("浏览器不支持SSE"); } }; ``` - 应用加载时onLaunch生命周期中调用此方法 - 新建一个页面显示store中存储的消息 ### 鸣谢 - [csdn**小猪乔治仔**](https://blog.csdn.net/qq_56251369/article/details/132849022) 标签: sse uniapp vue2 上一篇:后记《向阳生长,爱在感恩》文集 下一篇:若依项目添加新模块后报错nacos启动报错:Unable to start web server 随便看看 2026-01-12 后记《向阳生长,爱在感恩》文集 2026-01-12 《向阳生长,爱在感恩》文集 2026-01-12 自序《向阳生长,爱在感恩》文集 2026-01-12 序言《向阳生长,爱在感恩》文集 2026-01-08 如何使用mvn命令导入依赖 留言