uni-app连接EventSource
前言
uniapp
默认是不支持event-source
,这里是借助renderjs
进行SSE连接
正文
引入event-source-polyfill
这里演示的是直接将代码下载到本地进行引入
下载地址
把里面的eventsource.min.js
文件放到项目中的static
文件夹
项目封装event-source.vue
组件
<template>
<view :prop="info" :change:prop="sse.onChange" id="renderjs-view" />
</template>
<script>
import { BASE_URL } from "@/utils/config"
import { getToken } from "@/utils/auth"
import { storage } from "@/utils"
export default {
data() {
return {
info: {}
}
},
created() {
this.setInfo()
},
methods: {
setInfo() {
this.info = { url: BASE_URL, token: getToken(), userId: storage.getItem("userId") }
},
onMessage(e) {
this.$emit('message', e)
}
}
}
</script>
<script module="sse" lang="renderjs">
export default {
data() {
return {
sseInfo:{}
}
},
mounted() {
this.setSSE()
},
methods: {
setSSE() {
if (typeof EventSourcePolyfill === "function") {
this.initSSE()
} else {
const script = document.createElement('script')
script.src = "static/js/eventsource.min.js"
script.type = "text/javascript"
script.onload = this.initSSE.bind(this)
document.head.appendChild(script)
}
},
initSSE() {
const sse = new EventSourcePolyfill(`${this.sseInfo.url}/sse/system-sse/sse-server?userId=${this.sseInfo.userId}_${Date.now()}`, {
headers: {
Authorization: "Bearer " + this.sseInfo.token,
"Tenant-Id": 1
}
})
sse.onmessage = (e) => {
this.$ownerInstance.callMethod('onMessage', e)
}
},
onChange(value) {
this.sseInfo = value
},
}
}
</script>
外部使用
<EventSource @message="onMessage"/>
<script lang="ts" setup>
const onMessage = (e) => {
// uni.showModal({
// title: 'sse消息',
// content: e.data,
// })
console.log("sse消息:",e)
}
</script>