vue2、vue3中使用sse即时数据获取
·
1.安装插件
npm install event-source-polyfill --save
2.在页面中引入使用
<script lang="ts">
import { EventSourcePolyfill } from 'event-source-polyfill'
export default defineComponent({
setup(props, context) {
// 获取数据sse
function initEventSource() {
// 创建 EventSource 实例连接到服务器端点
const eventSource = new EventSourcePolyfill(
`http://xxxxx/xxxx` //url地址
)
// 监听消息
eventSource.onmessage = (event) => {
try {
//拿到数据咯,干点想干的
console.log(event)
} catch (e) {
console.error('解析消息时发生错误:', e)
}
}
// 监听连接打开事件
eventSource.onopen = () => {
// console.log('SSE 连接已打开。')
}
// 监听错误事件
eventSource.onerror = () => {
console.error('SSE 连接出错。')
// 可以在这里尝试重新连接或执行其他错误处理逻辑
}
}
onMounted(() => {
initEventSource()
})
return {
initEventSource
}
}
})
</script>
DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐

所有评论(0)