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

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

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

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

前端代码(Vue3 Composition API)

<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

  eventSource = new EventSource('http://192.168.14.231:5400/algWebflux/getLog')

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

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

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

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

<div class="text-container">
            {{ formattedText }}
          </div>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值