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发送的数据流界面已经完成了,样式还需要优化(现在是纯文字的界面),下一章介绍样式的优化,展示的代码编辑器样式优化。

相关推荐
驭风少年君9 分钟前
《搭建属于自己的网站之网页前端学习》基础入门
前端·学习
刘一说1 小时前
深入理解 Spring Boot 嵌入式 Web 容器:从原理到性能调优
前端·spring boot·firefox
你的人类朋友1 小时前
设计模式的原则有哪些?
前端·后端·设计模式
!执行2 小时前
Web3 前端与合约交互
前端·web3·1024程序员节
潘小安2 小时前
跟着 AI 学(二)- Quill 接入速通
前端
十里-2 小时前
在 Vue2 中为 Element-UI 的 el-dialog 添加拖拽功能
前端·vue.js·ui
shada2 小时前
从Google Chrome商店下载CRX文件
前端·chrome
左耳咚2 小时前
项目开发中从补码到精度丢失的陷阱
前端·javascript·面试
D_C_tyu2 小时前
Vue3 + Element Plus 实现前端手动分页
javascript·vue.js·elementui
黑云压城After2 小时前
vue2实现图片自定义裁剪功能(uniapp)
java·前端·javascript