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>
相关推荐
前端Hardy1 分钟前
HTML&CSS&JS:高颜值登录注册页面—建议收藏
前端·javascript·css
白雾茫茫丶3 分钟前
如何动态执行 JS 脚本
javascript
Ali酱4 分钟前
远程这两年,我才真正感受到——工作,原来可以不必吞噬生活。
前端·面试·远程工作
金金金__9 分钟前
优化前端性能必读:浏览器渲染流程原理全揭秘
前端·浏览器
Data_Adventure13 分钟前
Vue 3 手机外观组件库
前端·github copilot
泯泷18 分钟前
Tiptap 深度教程(二):构建你的第一个编辑器
前端·架构·typescript
黑幕困兽25 分钟前
vue 项目给输入框增加trim()方法
vue.js
屁__啦25 分钟前
前端错误-null结构
前端
lichenyang45325 分钟前
从0开始的中后台管理系统-5(userList动态展示以及上传图片和弹出创建用户表单)
前端
未来之窗软件服务29 分钟前
解析 div 禁止换行与滚动条组合-CSS运用
前端·css