vue处理接口返回EventStream数据并进行展示
1、在 Vue 组件中连接外部 SSE 接口
HTML:
<template>
<div class="ceshi-wrap">
<h3 style="color:red;">来自本地文件的 SSE 流数据:</h3>
-----
<ul>
<li v-for="item in messages" :key="item.id">
<span v-for="item1 in item" :key="item1.delta.timestamp" v-html="item1.delta.content" style="white-space: pre;">
</span>
</li>
</ul>
+++++
</div>
</template>
JS:
mounted() {
// http://localhost:3001/sse-stream 为返回EventStream数据的地址
const eventSource = new EventSource('http://localhost:3001/sse-stream');
// 监听消息事件
eventSource.onmessage = (event) => {
const data = JSON.parse(event.data);
this.messages.push(data.choices);
};
// 监听错误并关闭连接
eventSource.onerror = (error) => {
console.error('SSE Error:', error);
eventSource.close();
};
// 组件销毁时关闭连接(避免内存泄漏)
this.$once('hook:beforeDestroy', () => {
eventSource.close();
});
}
2、验证:启动vue项目
npm run serve
说明:
1)自动重连
EventSource 默认会在断开后尝试重连,可通过 eventSource.close() 手动关闭。
2)在使用v-html最后展示时,会把空格去掉,想要让空格正常显示的话,可以添加css:
white-space: pre;