vue接受流-springai+deepseek大模型结合数据库的智能客服

无敌的宇宙
无敌的宇宙
擅长邻域:Java,HTML,JavaScript,MySQL,支付,退款,图片上传

专栏: springai+deepseek大模型结合数据库的智能客服 标签: vue接受流

2026-06-20 15:06:50 6浏览

vue接受流
 // 注意:Vue2中直接操作 DOM 可能不会立即更新,建议用 nextTick 或确保元素已渲染
      this.$nextTick(() => {
        const replyDom = document.getElementById(id);
        if (!replyDom) return;

        // 【关键修改】使用原生 fetch 而不是封装的 chat 函数
        fetch( process.env.VUE_APP_API_ROOT+"/ai/chat", { // 替换为你的真实接口地址
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            // 'Authorization': 'Bearer YOUR_API_KEY' // 替换为你的 Key
          },
          body: JSON.stringify(userMessage)
        }).then(response => {
              if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
              }

              // 【关键点】获取 reader
              const reader = response.body.getReader();
              const decoder = new TextDecoder('utf-8');
              let fullText = '';

              const processStream = () => {
                reader.read().then(({ done, value }) => {
                  if (done) {
                    setTimeout(()=>{
                     this.getLastDataFunc(replyDom)
                    },500)


                    this.loading = false; 
                    return;
                  }

                  const chunkStr = decoder.decode(value, { stream: true }); // stream: true 处理多字节字符
                  const lines = chunkStr.split('\n').filter(line => line.trim() !== '');

                  for (const line of lines) {

                    if (line.startsWith('data:')) {

                      const jsonStr = line.replace('data:', '');
                      if (jsonStr === '[DONE]') continue;

                      if (jsonStr) {
                        fullText += jsonStr ;
                        // 实时更新 UI
                        replyDom.innerText = fullText;
                        this.scrollToBottom();
                      }

                    }
                  }

                  // 递归读取下一块
                  processStream();
                }).catch(error => {
                  console.error('Stream reading error:', error);
                  this.loading = false;
                });
              };

              processStream();
            })
            .catch(error => {
              console.error('Fetch error:', error);
              this.loading = false;
              replyDom.innerText = "请求失败: " + error.message;
            });
      });

好博客就要一起分享哦!分享海报

此处可发布评论

评论(0展开评论

暂无评论,快来写一下吧

展开评论

您可能感兴趣的博客

客服QQ 1913284695