后端使用的是?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>