若依 vue2 实现全局 Server-Sent Events (SSE)
时间: 2025-01-20 14:21:20 浏览: 161
### 实现基于Vue 2的全局Server-Sent Events (SSE)
为了在Vue 2项目中实现全局的Server-Sent Events (SSE),可以创建一个插件来管理`EventSource`实例,并将其挂载到Vue实例上以便在整个应用范围内访问。以下是具体方法:
#### 插件开发
首先,构建一个简单的Vue插件用于处理SSE连接。
```javascript
// plugins/sse.js
import Vue from 'vue';
const ssePlugin = {
install(Vue, options) {
let eventSource;
const initEventSource = () => {
if ('EventSource' in window) {
eventSource = new EventSource(options.url);
// 监听消息事件
eventSource.onmessage = function(event) {
Vue.prototype.$sseMessageHandler && Vue.prototype.$sseMessageHandler(event);
};
// 连接打开时触发
eventSource.onopen = function() {
Vue.prototype.$sseOpenHandler && Vue.prototype.$sseOpenHandler();
};
// 错误处理
eventSource.onerror = function(error) {
if (error.target.readyState === EventSource.CLOSED) {
console.error('Event Source closed.');
} else {
console.warn(`Error occurred (${error}). Attempting to reconnect.`);
setTimeout(() => {
initEventSource(); // 尝试重新建立连接
}, 5000); // 设置重连间隔时间
}
};
} else {
console.error('Your browser does not support Server Sent Events');
}
Vue.mixin({
beforeDestroy() {
if (this._isDestroyed && eventSource) {
eventSource.close();
}
},
});
Object.defineProperty(Vue.prototype, '$eventSource', {
get() { return eventSource; },
});
Object.defineProperty(Vue.prototype, '$closeEventSource', {
value: function() {
if (eventSource) {
eventSource.close();
}
},
});
};
initEventSource();
Vue.prototype.$addSSEListener = function(type, callback) {
if (!eventSource) throw new Error('EventSource is not initialized.');
eventSource.addEventListener(type, callback);
return () => {
eventSource.removeEventListener(type, callback);
};
};
Vue.prototype.$removeAllListeners = function() {
if (!eventSource) throw new Error('EventSource is not initialized.');
while (eventSource.listeners.length > 0) {
eventSource.removeEventListener(...eventSource.listeners.pop());
}
};
},
};
export default ssePlugin;
```
此代码片段展示了如何通过自定义插件的方式,在Vue 2应用程序中集成并控制`EventSource`的行为[^3]。
#### 使用插件
接着是在项目的入口文件(main.js)引入该插件,并配置必要的参数。
```javascript
// main.js
import Vue from 'vue';
import App from './App.vue';
import ssePlugin from './plugins/sse';
Vue.config.productionTip = false;
Vue.use(ssePlugin, {
url: '/your-server-endpoint',
});
new Vue({
render: h => h(App),
}).$mount('#app');
// 定义默认的消息处理器和其他钩子函数
Vue.prototype.$sseMessageHandler = function(message) {
console.log('Received message:', JSON.parse(message.data));
};
Vue.prototype.$sseOpenHandler = function() {
console.info('Connection opened successfully!');
};
```
上述设置允许开发者轻松地监听来自服务器的信息更新,并执行相应的逻辑操作[^4]。
阅读全文
相关推荐


















