在网页中添加deepseek,只需要改为自己的api-key
网页中嵌入deepseek
·
<template>
<div class="ai-assistant">
<div class="chat-container">
<div ref="messages" class="messages">
<div v-for="(msg, index) in messages" :key="index" :class="['message', msg.role]">
<div class="bubble">{{ msg.content }}</div>
</div>
</div>
<div class="input-area">
<input
v-model="inputMessage"
type="text"
placeholder="输入你的问题..."
@keyup.enter="sendMessage"
/>
<button @click="sendMessage" :disabled="loading">
{{ loading ? '思考中...' : '发送' }}
</button>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
inputMessage: '',
messages: [],
loading: false,
apiConfig: {
// 注意:正式环境应该通过环境变量管理
apiKey: '修改为自己的APIKEY',
endpoint: 'https://api.deepseek.com/v1/chat/completions'
}
};
},
methods: {
async sendMessage() {
if (!this.inputMessage.trim()) return;
const userMessage = this.inputMessage;
this.inputMessage = '';
this.addMessage(userMessage, 'user');
try {
this.loading = true;
const response = await axios.post(
this.apiConfig.endpoint,
{
model: 'deepseek-chat',
messages: [{ role: 'user', content: userMessage }]
},
{
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.apiConfig.apiKey}`
}
}
);
const aiResponse = response.data.choices[0].message.content;
this.addMessage(aiResponse, 'assistant');
} catch (error) {
console.error('API请求失败:', error);
this.addMessage('抱歉,暂时无法处理您的请求', 'error');
} finally {
this.loading = false;
this.scrollToBottom();
}
},
addMessage(content, role) {
this.messages.push({ content, role, timestamp: new Date() });
this.scrollToBottom();
},
scrollToBottom() {
this.$nextTick(() => {
const container = this.$refs.messages;
container.scrollTop = container.scrollHeight;
});
}
}
};
</script>
<style scoped>
/* 修改整体容器,使其占满整个浏览器窗口 */
.ai-assistant {
margin: 0px auto;
width: 80vw;
height: 90vh;
border: 1px solid #e0e0e0;
border-radius: 12px;
overflow: hidden;
}
/* 让聊天容器自适应父级高度 */
.chat-container {
height: 100%;
display: flex;
flex-direction: column;
}
.messages {
flex: 1;
padding: 20px;
overflow-y: auto;
background: #f5f5f5;
}
.message {
margin: 10px 0;
display: flex;
}
.message.user {
justify-content: flex-end;
}
.message.assistant {
justify-content: flex-start;
}
.bubble {
max-width: 70%;
padding: 12px 16px;
border-radius: 15px;
line-height: 1.5;
}
.user .bubble {
background: #007bff;
color: white;
}
.assistant .bubble {
background: white;
border: 1px solid #e0e0e0;
}
.error .bubble {
background: #ffebee;
color: #d32f2f;
}
.input-area {
padding: 20px;
background: white;
display: flex;
gap: 10px;
border-top: 1px solid #e0e0e0;
}
input {
flex: 1;
padding: 12px;
border: 1px solid #e0e0e0;
border-radius: 8px;
}
button {
padding: 12px 24px;
background: #007bff;
color: white;
border: none;
border-radius: 8px;
cursor: pointer;
}
button:disabled {
background: #cccccc;
cursor: not-allowed;
}
</style>
更多推荐

所有评论(0)