qx
qx
12 小时以前 495bf3ca62536c52cf78895501205965cae05828
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<template>
    <div>
      <h2>DeepSeek 聊天</h2>
      <textarea v-model="inputMessage" placeholder="请输入消息"></textarea>
      <button @click="sendMessage">发送</button>
      <p>回复: {{ reply }}</p>
      <p v-if="error" style="color: red">{{ error }}</p>
    </div>
  </template>
  
  <script>
  export default {
    name: 'Chat',
    data() {
      return {
        inputMessage: '',
        reply: '',
        error: ''
      };
    },
    methods: {
      async sendMessage() {
        if (!this.inputMessage.trim()) {
          this.error = '消息不能为空';
          return;
        }
        this.error = '';
        this.reply = '';
  
        try {
          const response = await fetch('http://localhost:3001/chat', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({ message: this.inputMessage })
          });
  
          if (!response.ok) {
            throw new Error('网络响应错误');
          }
  
          const reader = response.body.getReader();
          const decoder = new TextDecoder();
  
          while (true) {
            const { done, value } = await reader.read();
            if (done) break;
  
            const chunk = decoder.decode(value);
            const lines = chunk.split('\n').filter(line => line.trim());
            for (const line of lines) {                                          
              if (line.startsWith('data: ')) {
                const data = line.replace('data: ', '');
                if (data === '[DONE]') return;
                try {
                  const parsedData = JSON.parse(data);
                  const content = parsedData.choices[0].delta.content;
                  if (content) {
                    this.reply += content;
                  }
                } catch (err) {
                  console.error('解析错误:', err);
                }
              }
            }
          }
        } catch (err) {
          this.error = '流式响应出错';
          console.error('Fetch 错误:', err);
        }
      }
    }
  };
  </script>
  
  <style scoped>
  textarea {
    width: 300px;
    height: 100px;
    margin-bottom: 10px;
  }
  button {
    padding: 5px 10px;
  }
  </style>