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;
    });
}







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值