<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>
|