如何使用fetchEventSource實現(xiàn)sse流式請求
使用fetchEventSource實現(xiàn)sse流式請求
最近在項目開發(fā)的過程中,需要實現(xiàn)一個功能
根據(jù)進度條的進度動態(tài)實時加載獲取到的數(shù)據(jù)并展示出來

用到的是fetchEventSource
以下主要寫下js的實現(xiàn)的過程(前端用到的ui組件是antd-design-vue1.78版本 vue2.0項目)
首先下載插件:
npm install --save @microsoft/fetch-event-source
<div class="progress_container" v-if="!progressDone">
<div class="progress_row">
<a-progress type="line" :percent="progressValue" status="active" />
</div>
<div class="progress_text">
{{ progressTxt }}
</div>
</div>
<script>
import { fetchEventSource } from '@microsoft/fetch-event-source'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
export default {
data () {
return {
speed: 30,
progressValue: 0,//進度條初始值
progressTxt: '',//進度條文字展示默認值
eventSource: null,
abortController: null,
checkMessage: [],
checkResult: {},
resultData: [],
submitUnable: true,
progressDone: false
}
},
created () {
this.connectSSE()
},
destroyed () {
this.stopSSE()
},
methods: {
connectSSE () {
this.abortController = new AbortController() // 終止or結(jié)束會話,做了個全局的...
const url = process.env.VUE_APP_API_BASE_URL + `自己的請求數(shù)據(jù)接口`
const token = storage.get(ACCESS_TOKEN)
// 開始會話鏈接,也做了個全局的......
this.eventSource = fetchEventSource(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
[ACCESS_TOKEN]: token
},
// 傳參只能發(fā)送文本格式的數(shù)據(jù)
body: JSON.stringify({
}),
signal: this.abortController.signal,
onopen: (event) => {
console.log(event, 'SSE在連接打開時被調(diào)用')
},
onmessage: (event) => {
// console.log('SSE會在通過事件源收到數(shù)據(jù)時觸發(fā)')
// console.log('接口返回', JSON.parse(event.data))
//我這里是判斷我請求回來的數(shù)據(jù)里是否包含'[DONE]',他是數(shù)組里的最后一項,表示加載完成
if (!event.data.includes('[DONE]')) {
const data = JSON.parse(event.data)
const text = data.message
const percent = data.percent
const message = data.message
if (text === 'connect') {
// 連接成功,開始檢測邏輯
this.progressDone = false
this.progressValue = 0
this.progressTxt = '數(shù)據(jù)檢查中,該過程可能需要一段時間,請勿關(guān)閉窗口'
this.getTurnCheck()
return false
}
//定時器,控制進度條和文字的展示速度
this.speed += 300
this.timer = setTimeout(() => {
this.progressValue = Number(percent)
this.progressTxt = message
if (this.progressValue === 100 && !this.progressDone) {
this.stopSSE()
}
}, this.speed)
}
if (event.data.includes('[DONE]')) {
}
},
onerror: () => {
console.log('SSE拋出異常onerror')
this.stopSSE()
},
// onclose函數(shù)是會話結(jié)束正常關(guān)閉觸發(fā),但幾乎沒有做到這步,不執(zhí)行這個回調(diào),不知道什么原因
onclose: () => {
console.log('onclose')
}
})
},
// 停止SSE
async stopSSE () {
// 關(guān)閉業(yè)務,執(zhí)行關(guān)閉sse數(shù)據(jù)接口
await this.getCloseSse()
if (this.abortController) {
this.timer && clearTimeout(this.timer)
console.log('SSE結(jié)束會話了')
this.abortController.abort() // 結(jié)束會話
}
},
//檢查數(shù)據(jù)的接口
async getTurnCheck () {
const params = {
}
},
//關(guān)閉sse接口
async getCloseSse () {
const params = {
}
const [err, res] = await to(closeSse(params))
if (err) return false
}
},
}
</script>總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue-admin-template?動態(tài)路由的實現(xiàn)示例
本文主要介紹了ue-admin-template動態(tài)路由的實現(xiàn),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-12-12
SpringBoot+Vue3實現(xiàn)文件的上傳和下載功能
上傳文件和下載文件是我們平時經(jīng)常用到的功能,接下來就讓我們用SpringBoot,Vue3和ElementPlus組件實現(xiàn)文件的上傳和下載功能吧,感興趣的朋友跟隨小編一起看看吧2023-01-01
vue2.0實現(xiàn)的tab標簽切換效果(內(nèi)容可自定義)示例
這篇文章主要介紹了vue2.0實現(xiàn)的tab標簽切換效果,結(jié)合實例形式分析了vue.js實現(xiàn)內(nèi)容可自定義的tab點擊切換功能相關(guān)操作技巧,需要的朋友可以參考下2019-02-02
Vue3計算屬性computed和監(jiān)聽屬性watch區(qū)別解析
計算屬性適用于對已有的數(shù)據(jù)進行計算,派生新的數(shù)據(jù),并在模板中使用;而監(jiān)聽屬性適用于監(jiān)聽數(shù)據(jù)的變化,并執(zhí)行一些特定的操作,根據(jù)具體的需求和場景,選擇適合的機制這篇文章主要介紹了Vue3計算屬性computed和監(jiān)聽屬性watch,需要的朋友可以參考下2024-02-02
vue如何使用formData傳遞文件類型的數(shù)據(jù)
這篇文章主要介紹了vue如何使用formData傳遞文件類型的數(shù)據(jù)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05
vue如何通過ref調(diào)用router-view子組件的方法
這篇文章主要介紹了vue?通過ref調(diào)用router-view子組件的方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2023-11-11

