1:安装
npm install event-source-polyfill
2:在store.js中引入
import { EventSourcePolyfill } from "event-source-polyfill";
3:在state中定义new EventSourcePolyfill的实例用作保存
state: {eventSource: null},
4:在actions中使用
// 连接ssejoinSse({ commit, dispatch, state }, token) {/* 如果state中eventSource存在实例,需要先清除之前的 */if (state.eventSource) {state.eventSource.close();}/* cs() */let url = process.env.VUE_APP_SSE_API + "/create";console.log('sse地址', url)return new Promise((resolve) => {state.eventSource = new EventSourcePolyfill(url, {withCredentials: true,heartbeatTimeout: 1000 * 60 * 30,headers: {Authorization: "Bearer " + token,contentType: "application/json;charset=utf-8",},});state.eventSource.onerror = function(err) {/* 链接失败,重新连接,我这边加了token判断是否登录 */state.eventSource.close();if (getToken()) {setTimeout(() => {dispatch("joinSse", getToken());}, 30000)}};state.eventSource.onopen = function(open) {console.log("连接成功", open);};state.eventSource.onmessage = function(e) {let data = JSON.parse(e.data);console.log("接受消息===============", data);//在这里你将得到自己想要的消息内容,可进行其他操作};});},