Vue3连接SSE,并且返回结果用打字机效果呈现

话不多说 直接上代码

连接SSE

vue3 复制代码
<script setup>
import { ref,onMounted,onUnmounted } from 'vue';
const sse = ref()
const reconnectAttempts = ref(0)
const timer = ref()
onMounted(()=>{
    initSSE();
})
onUnmounted(() => {
    if (sse.value) {
        sse.value.close();
    }
    // 清除定时器
    clearTimeout(timer.value);
});
const initSSE = () => {
    sse.value = new EventSource(`http://192.168.16.18:8888/sse/subscribe?userId=1`);
    sse.value.onopen = function (e) {
        console.log(e, "连接成功");
        reconnectAttempts.value = 0; // 重置重连次数
    };
    sse.value.onmessage = (event) => {
        console.log(event.data)
    }
    sse.value.onerror = (error) => {
        console.error("SSE 连接出错:", error);
        sse.value.close();
        sse.value = null;
        // 自动重连逻辑
        reconnectAttempts.value++;
        const reconnectDelay = Math.min(30000, 1000 * Math.pow(2, reconnectAttempts.value)); // 计算重连延迟,最大延迟为30秒
        console.log(`将在 ${reconnectDelay} 毫秒后尝试重连...`);
        // 等待一定时间后重连
        setTimeout(() => {
            if (!sse.value) {
                console.log("尝试重连 SSE...");
                initSSE(); // 递归调用重连
            }
        }, reconnectDelay);
    }
}
</script>

返回值加入打字机效果

vue3 复制代码
<script>
import { ref,onMounted,onUnmounted } from 'vue';
const sse = ref()
const reconnectAttempts = ref(0)
const contentList = ref([])//对话列表
const fullText = ref("")
const timer = ref()
onMounted(()=>{
    initSSE();
})
onUnmounted(() => {
    if (sse.value) {
        sse.value.close();
    }
    // 清除定时器
    clearTimeout(timer.value);
});
// 打字机效果的方法
const typeWriterEffect = () => {
    if (fullText.value.length > 0) {
        contentList.value[contentList.value.length - 1].content += fullText.value[0];
        fullText.value = fullText.value.slice(1);
        // 设置打字速度(例如每 100 毫秒显示一个字符)
        timer.value = setTimeout(typeWriterEffect, 100);
        if (fullText.value == "") {
            //打字机效果结束后关闭加载效果,这里可以自由发挥
            contentList.value[contentList.value.length - 1].show = false
        }
        //滚动到底部的距离
        scrollToBottom();
    }
};
const initSSE = () => {
    sse.value = new EventSource(`http://192.168.16.18:8888/sse/subscribe?userId=1`);
    sse.value.onopen = function (e) {
        console.log(e, "连接成功");
        reconnectAttempts.value = 0; // 重置重连次数
    };
    sse.value.onmessage = (event) => {
        console.log(event.data)
        fullText.value += event.data;
        // 开始打字机效果
        typeWriterEffect();
    }
    sse.value.onerror = (error) => {
        console.error("SSE 连接出错:", error);
        sse.value.close();
        sse.value = null;
        // 自动重连逻辑
        reconnectAttempts.value++;
        const reconnectDelay = Math.min(30000, 1000 * Math.pow(2, reconnectAttempts.value)); // 计算重连延迟,最大延迟为30秒
        console.log(`将在 ${reconnectDelay} 毫秒后尝试重连...`);
        // 等待一定时间后重连
        setTimeout(() => {
            if (!sse.value) {
                console.log("尝试重连 SSE...");
                initSSE(); // 递归调用重连
            }
        }, reconnectDelay);
    }
}
</script>

这时候根据SSE发送的数据流界面已经完成了,样式还需要优化(现在是纯文字的界面),下一章介绍样式的优化,展示的代码编辑器样式优化。

相关推荐
掘金安东尼几秒前
抛弃自定义模态框:原生Dialog的实力
前端·javascript·github
hj5914_前端新手4 小时前
javascript基础- 函数中 this 指向、call、apply、bind
前端·javascript
薛定谔的算法4 小时前
低代码编辑器项目设计与实现:以JSON为核心的数据驱动架构
前端·react.js·前端框架
Hilaku4 小时前
都2025年了,我们还有必要为了兼容性,去写那么多polyfill吗?
前端·javascript·css
yangcode4 小时前
iOS 苹果内购 Storekit 2
前端
LuckySusu4 小时前
【js篇】JavaScript 原型修改 vs 重写:深入理解 constructor的指向问题
前端·javascript
LuckySusu4 小时前
【js篇】如何准确获取对象自身的属性?hasOwnProperty深度解析
前端·javascript
LuckySusu4 小时前
【js篇】深入理解 JavaScript 作用域与作用域链
前端·javascript
LuckySusu4 小时前
【js篇】call() 与 apply()深度对比
前端·javascript
LuckySusu4 小时前
【js篇】addEventListener()方法的参数和使用
前端·javascript