Vue3——如何读取chatgpt的流式数据

一、实现效果图

二、读取数据

下图是gpt返回的流式数据的数据形式,那么我们怎么把这个数据放到页面中,以实现gpt的打字机效果呢?

javascript 复制代码
const response = await fetch(baseURLs + "/api/ut/plan/smartWriteStream", {
      method: "POST",
      body: JSON.stringify(par),
      headers: {
        "Content-Type": "application/json",
        Accept: "text/event-stream",
        tk: localStorage.getItem("token"),
      },
    });
    searchCon.value = "";
    const encode = new TextDecoder("utf-8");
    const reader = response.body.getReader();
    while (true) {
      const { done, value } = await reader.read();
      const decodeText = encode.decode(value);
      // console.log(decodeText, "流式数据");

      // 读取结束
      if (done) {
        isShowstopBtn.value = false;
        isShowconfirmBtn.value = true;
        break;
      }


      if (isAddText.value) {
        longText.value += getReaderText(decodeText);
        setTimeout(() => {
          if (scrollbarRef.value) {
            let ele = document.getElementById("innerRef");
            const max = ele.clientHeight;
            scrollbarRef.value[0].setScrollTop(max * 1 + 1000000);
          }
        }, 300);
      } else {
        break;
      }
    }

三、处理流式数据中的特殊字符

javascript 复制代码
const getReaderText = (str) => {
  let matchStr = "";
  try {
    let resultList = str.trim().split("\n");
    resultList.forEach((item) => {
      const firstQuoteIndex = item.indexOf('"');
      const lastQuoteIndex = item.lastIndexOf('"');
      matchStr += item
        .substring(firstQuoteIndex + 1, lastQuoteIndex)
        .replace("\\n\\n", "")
        .replace("\n\n", "")
        .replace("\\n", "")
        .replace("\n", "")
        .replace("\\\\", "")
        .replace("\\", "");
    });
    // console.log(resultList, "4444");
  } catch (e) {
    // console.log(e);
  }
  // console.log(matchStr);
  return matchStr;
};
相关推荐
huohaiyu4 小时前
从URL到页面的完整解析流程
前端·网络·chrome·url
阿星AI工作室6 小时前
一个简单Demo彻底理解前后端怎么连的丨Figma + Supabase + Vercel
前端·人工智能
aircrushin6 小时前
一拍即传的平替,完全免费的实时照片墙!
前端
光的方向_8 小时前
从原理到实践:深度解析Transformer架构——大模型时代的核心基石
人工智能·chatgpt·prompt·transformer
鹏北海8 小时前
JSBridge 原理详解
前端
孟健8 小时前
我的网站被黑了:一天灌入 227 万条垃圾数据,AI 写的代码差点让我社死
前端
anOnion8 小时前
构建无障碍组件之Checkbox pattern
前端·html·交互设计
IT枫斗者10 小时前
IntelliJ IDEA 2025.3史诗级更新:统一发行版+Spring Boot 4支持,这更新太香了!
java·开发语言·前端·javascript·spring boot·后端·intellij-idea
N***p36510 小时前
Spring Boot项目接收前端参数的11种方式
前端·spring boot·后端
享誉霸王11 小时前
15、告别混乱!Vue3复杂项目的规范搭建与基础库封装实战
前端·javascript·vue.js·前端框架·json·firefox·html5