用一个messages数组来存放对话信息,信息有两种类型user和bot
this.messages.push({ type: 'user', content: this.userMessage });
this.messages.push({ type: 'bot', content: response.data.reply });
模版部分使用:class="['message-content', message.type]将两种对话数据区分开来(不要忘记冒号)
相关css实现
.message-item {
margin-right: 15%;
margin-left: 15%;
display: flex;
justify-content: flex-end; /* 将用户消息放在右侧 */
margin-bottom: 10px;
}
.message-item.bot {
justify-content: flex-start; /* 将机器人消息放在左侧 */
}
.message-content {
padding: 10px;
border-radius: 10px;
background-color: #DCF8C6; /* 用户消息背景色 */
max-width: 100%;
word-wrap: break-word;
}
.message-content.bot {
background-color: #E0E0E0; /* 机器人消息背景色 */
}
scrollToBottom() {
var div = document.getElementById('message');
div.scrollTop = div.scrollHeight;
},
利用axios作为请求,用GET方法
注意,axios与request是有区别的,axios相比于request的返回数据被多封装了一层,用response.data.reply来获取数据
async sendToBackend(message) {
try {
const response = await axios.get('YOUR_BACKEND_API_URL', {
message: message
});
// 假设后端返回的数据在response.data中
this.messages.push({ type: 'bot', content: response.data.reply });
} catch (error) {
console.error('Error sending message:', error);
// 可以添加错误处理逻辑
this.messages.push({ type: 'bot', content: '出错了,请稍后再试。' });
}
},
:global(body) {
margin: 0; /* 去除页面的默认边距 */
padding: 0; /* 去除页面的默认内边距 */
overflow: hidden; /* 隐藏所有内容的滚动条 */
}
创建新对话,查看历史对话
对于历史记录部分通过for循环来进行展示
创建新对话
{{ messages[0] ? messages[0].content : '您还没有提问问题' }}
历史
{{ history[0] ? history[0].content : 'No content available' }}
在点击历史记录的时候会将当前的对话保存,再对历史记录进行展示
async getHistories() { // 获取历史数据
try {
console.log("Fetching histories..."); // 添加一个日志以确保函数调用正常
const response = await axios.get('http://127.0.0.1:5000/histories');
// 假设后端返回的数据在response.data中
this.histories = response.data; // 将返回的数据存储在组件的 histories 属性中
console.log(this.histories); // 打印获取的历史数据,以便调试和确认
console.log(this.sortedHistories)
} catch (error) {
console.error('Error fetching histories:', error); // 如果出现错误,打印错误信息
// 可以添加更详细的错误处理逻辑,比如显示错误信息到界面上
console.log("Failed to fetch histories."); // 日志记录数据获取失败
}
}
,
saveHistory() {
if (this.messages && this.messages.length > 0 && !this.passOld) {
this.histories.push(this.messages);
}
}
,