关于使用event-source-polyfill单向实时监听接口数据的简单实现
EventSourcePolyfill 是一个用于在老版本浏览器上模拟Server-Sent Events(SSE)的 polyfill。SSE 是一种允许服务器向客户端推送实时更新的技术。EventSourcePolyfill 通过在不支持原生 EventSource API 的浏览器中提供相应的功能,从而增强了 SSE 的浏览器兼容性。 
安装 EventSourcePolyfill:
npm install event-source-polyfill --save
yarn install event-source-polyfill
代码示例
<template>
  <div class="demo-container">
        <div class="every-count">总人数:{{ countInfo?.count || 0 }}</div>
  </div>
</template>
<script setup>
import { EventSourcePolyfill } from 'event-source-polyfill'
const userPinia = useUserPinia()
const countInfo = ref({}
const evtSource = ref(null) //EventSource实例
const initEventSource = () => {
  if (typeof EventSource !== 'undefined') {
    const evtConfig = {
      headers: {
        Authorization: userPinia.getAccessToken || '',
      },
      isClient: true,
      heartbeatTimeout: 7 * 24 * 60 * 60 * 1000, //重连时间,ms,默认设置7天
      withCredentials: true,
    }
    const evtUrl = `${baseUrl}/meeting/business/ksmMeetingCheckIn/subscribe?id=xxx`
    evtSource.value = new EventSourcePolyfill(evtUrl, evtConfig)
    // 监听连接打开事件
    evtSource.value.onopen = function (e) {}
    // 监听 'message' 事件,当服务器发送新数据时触发
    evtSource.value.onmessage = function (e) {
      // e.data 包含从服务器接收到的数据(通常是 JSON 字符串)
      try {
        countInfo.value = JSON.parse(e.data)
      } catch (error) {
        console.error('Error parsing JSON:', error)
      }
    }
    // 监听连接错误事件
    evtSource.value.onerror = function (e) {
      evtSource.value.close() // 关闭连接
    }
  } else {
    ElMessage.warning('当前浏览器不支持使用EventSource接收服务器推送事件!')
  }
}
onMounted(() => {
  initEventSource()
})
onBeforeUnmount(() => {
  evtSource.value.close()
})
</script>
 
    
    

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号