24.中医知识问答删除历史对话功能前端代码实现
前端实现对话删除功能的完整指南
功能概述
前篇文章介绍了删除历史对话的后端开发,本篇将介绍如何在前端实现一个完整的对话删除功能,包括用户确认、API调用、状态管理和错误处理等关键环节。
功能拆解
1. 用户确认机制
javascript
const confirmDelete = confirm(“确定要删除这个会话吗?”);
if (!confirmDelete) return;
设计要点:
使用浏览器原生confirm对话框
防止用户误操作
简单直接的交互方式
2. API请求处理
javascript
axios.delete(http://localhost:8080/api/chat/conversations/${convId}
)
最佳实践:
使用RESTful风格的API端点
明确HTTP方法(DELETE)
包含完整的URL路径
3. 响应成功处理
javascript
this.conversations = this.conversations.filter(conv => conv.id !== convId);
if (this.currentConversation && this.currentConversation.id === convId) {
this.currentConversation = null;
this.messages = [];
}
状态管理:
从对话列表中过滤掉已删除项
检查并清理当前会话状态
保持UI与数据同步
4. 错误处理机制
javascript
.catch((error) => {
const errorMsg = error.response?.data?.message || error.message || “请求失败”;
this.$message.error(删除失败: ${errorMsg}
);
})
错误处理策略:
网络错误
API返回错误
未知错误兜底
用户友好的错误提示
5. 最终状态清理
javascript
.finally(() => {
this.activeDropdown = null;
});
UI一致性:
无论成功失败都关闭操作菜单
保持界面整洁
完整代码实现
deleteConversation(convId) {// 添加确认对话框const confirmDelete = confirm("确定要删除这个会话吗?");if (!confirmDelete) return; // 用户点击取消axios.delete(`http://localhost:8080/api/chat/conversations/${convId}`).then((response) => {if (response && response.status === 200) {// 更新本地状态this.conversations = this.conversations.filter(conv => conv.id !== convId);// 清理当前会话状态if (this.currentConversation && this.currentConversation.id === convId) {this.currentConversation = null;this.messages = [];}} else {console.error("删除失败,未返回成功响应", response);const errorMsg = response.data?.message || "无法删除此会话";this.$message.error(`删除失败: ${errorMsg}`);}}).catch((error) => {console.error("请求错误", error);const errorMsg = error.response?.data?.message || error.message || "请求失败";this.$message.error(`删除失败: ${errorMsg}`);}).finally(() => {this.activeDropdown = null;});
}