vue3接收流式消息
时间: 2025-08-15 17:34:03 AIGC 浏览: 16
### Vue3 中实现接收流式消息的功能
在前端开发中,通过 `EventSource` 可以轻松实现服务端事件(SSE, Server-Sent Events)。以下是基于 Node.js 和 Vue3 的解决方案。
#### 前提条件
为了使 SSE 正常工作,后端返回的数据需遵循特定格式。例如,每条消息应以 `data:` 开头,并以两个换行符结束[^1]。如果未按照此标准格式化数据,则浏览器端的 `onmessage` 函数可能无法接收到数据。
---
#### 后端 (Node.js) 配置示例
以下是一个简单的 Node.js 脚本用于模拟 SSE 流:
```javascript
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/events') {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
setInterval(() => {
const data = JSON.stringify({ time: new Date().toISOString() });
res.write(`data: ${data}\n\n`);
}, 1000);
} else {
res.end('Hello World');
}
});
server.listen(8080, () => console.log('Server is running on port 8080'));
```
上述代码创建了一个 HTTP 服务器,在访问 `/events` 路径时会持续向客户端推送时间戳数据。
---
#### 前端 (Vue3) 接收流式消息
在 Vue3 应用程序中可以使用原生 JavaScript 提供的 `EventSource` API 来监听来自后端的消息。下面是一段完整的 Vue 组件示例代码:
```vue
<template>
<div>
<h1>实时更新的时间</h1>
<ul>
<li v-for="(item, index) in messages" :key="index">{{ item.time }}</li>
</ul>
</div>
</template>
<script>
import { ref, onMounted, onUnmounted } from 'vue';
export default {
setup() {
const messages = ref([]);
const connectToStream = () => {
const eventSource = new EventSource('http://localhost:8080/events'); // 替换为实际 URL
eventSource.onopen = () => {
console.log('连接已建立');
};
eventSource.onerror = (error) => {
console.error('发生错误:', error);
eventSource.close();
};
eventSource.onmessage = (event) => {
try {
const parsedData = JSON.parse(event.data); // 解析数据
messages.value.push(parsedData); // 添加到列表
} catch (e) {
console.warn('解析失败:', e.message);
}
};
};
onMounted(connectToStream);
onUnmounted(() => {
const eventSource = new EventSource('http://localhost:8080/events');
eventSource.close(); // 关闭连接以防内存泄漏
});
return { messages };
},
};
</script>
```
在此组件中:
- 使用了 Composition API (`ref`, `onMounted`, `onUnmounted`)。
- 当页面加载完成时调用 `connectToStream` 方法来初始化 `EventSource` 连接。
- 数据被推送到数组 `messages` 并动态渲染至 DOM 上。
---
#### 注意事项
1. **跨域支持**: 如果前后端不在同一域名下,请确保后端配置 CORS 头部允许跨域请求。
2. **断线重连机制**: 默认情况下,当网络中断或超时时,`EventSource` 会在几秒后自动尝试重新连接。
3. **性能优化**: 对于高频率的消息推送场景,建议考虑 WebSocket 或其他更高效的协议替代 SSE。
---
阅读全文
相关推荐




















