如何使用fetchEventSource實(shí)現(xiàn)sse流式請求
使用fetchEventSource實(shí)現(xiàn)sse流式請求
最近在項(xiàng)目開發(fā)的過程中,需要實(shí)現(xiàn)一個功能
根據(jù)進(jìn)度條的進(jìn)度動態(tài)實(shí)時加載獲取到的數(shù)據(jù)并展示出來
用到的是fetchEventSource
以下主要寫下js的實(shí)現(xiàn)的過程(前端用到的ui組件是antd-design-vue1.78版本 vue2.0項(xiàng)目)
首先下載插件:
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,//進(jìn)度條初始值 progressTxt: '',//進(jìn)度條文字展示默認(rèn)值 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ù)組里的最后一項(xiàng),表示加載完成 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 } //定時器,控制進(jìn)度條和文字的展示速度 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è)務(wù),執(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)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue-admin-template?動態(tài)路由的實(shí)現(xiàn)示例
本文主要介紹了ue-admin-template動態(tài)路由的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-12-12SpringBoot+Vue3實(shí)現(xiàn)文件的上傳和下載功能
上傳文件和下載文件是我們平時經(jīng)常用到的功能,接下來就讓我們用SpringBoot,Vue3和ElementPlus組件實(shí)現(xiàn)文件的上傳和下載功能吧,感興趣的朋友跟隨小編一起看看吧2023-01-01Vue3如何使用axios發(fā)起網(wǎng)絡(luò)請求
這篇文章主要介紹了Vue3如何使用axios發(fā)起網(wǎng)絡(luò)請求,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06vue2.0實(shí)現(xiàn)的tab標(biāo)簽切換效果(內(nèi)容可自定義)示例
這篇文章主要介紹了vue2.0實(shí)現(xiàn)的tab標(biāo)簽切換效果,結(jié)合實(shí)例形式分析了vue.js實(shí)現(xiàn)內(nèi)容可自定義的tab點(diǎn)擊切換功能相關(guān)操作技巧,需要的朋友可以參考下2019-02-02Vue3計算屬性computed和監(jiān)聽屬性watch區(qū)別解析
計算屬性適用于對已有的數(shù)據(jù)進(jìn)行計算,派生新的數(shù)據(jù),并在模板中使用;而監(jiān)聽屬性適用于監(jiān)聽數(shù)據(jù)的變化,并執(zhí)行一些特定的操作,根據(jù)具體的需求和場景,選擇適合的機(jī)制這篇文章主要介紹了Vue3計算屬性computed和監(jiān)聽屬性watch,需要的朋友可以參考下2024-02-02vue如何使用formData傳遞文件類型的數(shù)據(jù)
這篇文章主要介紹了vue如何使用formData傳遞文件類型的數(shù)據(jù)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05Vue使用jsmind實(shí)現(xiàn)生成腦圖的示例代碼
這篇文章主要為大家詳細(xì)介紹了Vue如何使用jsmind實(shí)現(xiàn)生成腦圖,文中的示例代碼講解詳細(xì),具有一定的借鑒價值,有需要的小伙伴可以參考一下2024-03-03vue中watch的實(shí)際開發(fā)學(xué)習(xí)筆記
watch是Vue實(shí)例的一個屬性是用來響應(yīng)數(shù)據(jù)的變化,需要在數(shù)據(jù)變化時執(zhí)行異步或開銷較大的操作時,這個方式是最有用的,下面這篇文章主要給大家介紹了關(guān)于vue中watch的實(shí)際開發(fā)筆記,需要的朋友可以參考下2022-11-11vue如何通過ref調(diào)用router-view子組件的方法
這篇文章主要介紹了vue?通過ref調(diào)用router-view子組件的方法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2023-11-11