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

相关推荐
青茶360几秒前
php怎么实现订单接口状态轮询(二)
前端·php·接口
大橙子额43 分钟前
【解决报错】Cannot assign to read only property ‘exports‘ of object ‘#<Object>‘
前端·javascript·vue.js
RFCEO44 分钟前
前端编程 课程十六、:CSS 盒子模型
css·前端基础课程·css盒子模型·css盒子模型的组成·精准控制元素的大小和位置·css布局的基石·内边距(padding)
LYFlied2 小时前
从 Vue 到 React,再到 React Native:资深前端开发者的平滑过渡指南
vue.js·react native·react.js
爱喝白开水a2 小时前
前端AI自动化测试:brower-use调研让大模型帮你做网页交互与测试
前端·人工智能·大模型·prompt·交互·agent·rag
董世昌412 小时前
深度解析ES6 Set与Map:相同点、核心差异及实战选型
前端·javascript·es6
B站_计算机毕业设计之家2 小时前
豆瓣电影数据采集分析推荐系统 | Python Vue Flask框架 LSTM Echarts多技术融合开发 毕业设计源码 计算机
vue.js·python·机器学习·flask·echarts·lstm·推荐算法
吃杠碰小鸡3 小时前
高中数学-数列-导数证明
前端·数学·算法
kingwebo'sZone3 小时前
C#使用Aspose.Words把 word转成图片
前端·c#·word
xjt_09014 小时前
基于 Vue 3 构建企业级 Web Components 组件库
前端·javascript·vue.js