自学内容网 自学内容网

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>

原文地址:https://blog.csdn.net/AK852369/article/details/145266256

免责声明:本站文章内容转载自网络资源,如侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!