vue3接收SSE流数据进行实时渲染日志

后端使用的是 Spring Boot WebFlux (响应式编程框架),并且返回的是 Server-Sent Events (SSE) 流式数据,那么在 Vue3 中,需要使用 EventSource APIfetch + 流式读取 来正确获取响应内容。

方案 1:使用 EventSource(推荐,兼容 SSE 标准)

如果你的后端返回的是标准的 SSE 数据流(Content-Type: text/event-stream),可以直接用浏览器原生的 EventSource 监听数据:

前端代码(Vue3 Composition API)

javascript 复制代码
<script setup>
import { onMounted, onUnmounted, ref } from "vue";

const logContent = ref('') // 存储日志内容
const logContainer = ref(null)
const error = ref(null)
let eventSource = null

// 对后端返回的数据做换行
const formattedText = computed(() => {
  return logContent.value.replace(/#n/g, '\n')
})
// 封装连接 SSE 的逻辑
const connectToLogStream = () => {
  eventSource = new EventSource('/api/algWebflux/getLog')
  eventSource.onmessage = (event) => {
    // 新内容追加到已有内容下方,并转换 #n 为换行符
    logContent.value += event.data.replace(/#n/g, '\n') + '\n\n'
    // 自动滚动到底部
    scrollToBottom()
    eventSource.onerror = (err) => {
      console.error('SSE error:', err)
      // 5秒后自动重连
      setTimeout(connectSSE, 5000)
    }
  }

  eventSource.onerror = (err) => {
    error.value = '日志流连接失败'
    console.error('SSE Error:', err)
  }
}

const scrollToBottom = () => {
  nextTick(() => {
    if (logContainer.value) { // 确保元素存在
      logContainer.value.scrollTop = logContainer.value.scrollHeight
    }
  })
}

 // 组件挂载时调用
onMounted(() => {
  connectToLogStream()
});

// 组件卸载时关闭连接
onUnmounted(() => {
  if (eventSource) eventSource.close()
})
</script>

如果代码中调用接口写成这种方式报错跨域错误(如 No 'Access-Control-Allow-Origin' header

javascript 复制代码
  eventSource = new EventSource('http://192.168.14.231:5400/algWebflux/getLog')

那就需要在 vite.config.js 中配置

javascript 复制代码
export default defineConfig({
  server: {
    proxy: {
      '/api': {
        target: 'http://192.168.14.231:5400',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      }
    }
  }
})

然后前端请求 /api/algWebflux/getLog

最后在页面进行渲染就可以了

html 复制代码
<div class="text-container">
            {{ formattedText }}
          </div>
相关推荐
人民广场吃泡面12 小时前
前端该重视的编程思想
前端
冬夜戏雪12 小时前
agent的trace 和eval
开发语言·前端·javascript
IT_陈寒12 小时前
Redis的DEL命令居然没删干净数据?这个坑我爬了半天
前端·人工智能·后端
kyriewen12 小时前
面试官让我现场用 AI 改一个真实 bug——他打断我的 3 个理由
前端·面试·ai编程
计算机魔术师13 小时前
斯坦福研究:AI 对入门级岗位冲击最大
前端
感谢一路走过的人13 小时前
AGGrid刷新数据后执行筛选
javascript·ag-grid
水獭比特14 小时前
工具都批准了,为什么还不能执行?给 Agent 补上第二道校验
javascript·人工智能·node.js
Simon_He14 小时前
一个渲染内核,五个框架包:我的流式 Markdown 渲染库是怎么长成“全家桶”的
前端·vue.js·markdown