前端實現對話刪除功能的完整指南
功能概述
前篇文章介紹了刪除歷史對話的后端開發,本篇將介紹如何在前端實現一個完整的對話刪除功能,包括用戶確認、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;});
}