uniapp vue2版本使用sse通信 日期:2025-04-08 人气:5 - 定义一个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 随便看看 2025-09-18 七棵菜表单快速开发平台二次开发步骤 2025-09-12 手动更新composer包 2025-08-25 blender4.5实现平面投影切割 2025-08-22 blender4.5.1操作说明 2025-08-19 查看composer所有依赖的 PHP 版本要求 留言