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

相关推荐
0思必得012 小时前
[Web自动化] Selenium获取元素的子元素
前端·爬虫·selenium·自动化·web自动化
用户57573033462412 小时前
🌟 从一行 HTML 到屏幕像素:浏览器是如何“画”出网页的?
前端
NEXT0612 小时前
React Hooks 进阶:useState与useEffect的深度理解
前端·javascript·react.js
sure28212 小时前
React Native应用中使用sqlite数据库以及音乐应用中的实际应用
前端·react native
CHU72903512 小时前
扭蛋机盲盒小程序前端功能设计解析:打造趣味与惊喜并存的消费体验
前端·小程序
哈里谢顿12 小时前
CSS 入门完全指南:从零构建你的第一个样式表
css
前端布道师12 小时前
Web响应式:列表自适应布局
前端
ZeroTaboo12 小时前
rmx:给 Windows 换一个能用的删除
前端·后端
哈里谢顿12 小时前
Vue 3 入门完全指南:从零构建你的第一个响应式应用
vue.js
李剑一12 小时前
Vue实现大屏获取当前所处城市及当地天气(纯免费)
前端