Vue3结合Axios按ID删除JSON数据时出现Uncaught TypeError报错
错误成因
- 直接原因是调用
deleteToDo方法时传入的参数todoList为undefined,尝试读取它的id属性时抛出了类型错误,具体可分为以下几种常见场景:
- 模板绑定删除事件时未传参,比如只写了
@click="deleteToDo",没有传入当前对应的待办项对象 - v-for循环的变量名和传递给删除方法的参数不匹配,比如循环变量是
item in todoList,调用方法时没有传入item - 新增数据后没有同步更新本地的待办列表数组,导致列表项绑定的数据本身无效
解决办法
- 首先检查模板的事件绑定写法,确保调用删除方法时正确传入当前循环的待办项对象,参考写法:
<template> <div v-for="item in todoList" :key="item.id"> <span>{{ item.description }}</span> <button @click="deleteToDo(item)">删除</button> </div> </template>
- 给删除方法添加参数校验,避免运行时报错,同时补充删除成功后的本地数组同步逻辑,保证页面同步更新:
deleteToDo(todoItem){ if(!todoItem || !todoItem.id) return console.warn('待删除项数据无效') axios.delete(`http://localhost:3000/todoList/${todoItem.id}`).then(response_delete =>{ console.log(response_delete) // 同步删除本地数组中对应的项 const targetIndex = this.todoList.findIndex(item => item.id === todoItem.id) if(targetIndex > -1) this.todoList.splice(targetIndex, 1) }) .catch(error => { console.log(error) }) }
- 优化新增逻辑,新增成功后要将接口返回的完整数据(包含服务端生成的id)推入本地数组,不要直接使用提交的无id的
sendData:
addToDo(e){ const sendData = { description : e.target.value, date : new Date() } axios.post('http://localhost:3000/todoList', sendData).then(response_result =>{ console.log(response_result) // 将带id的新数据加入本地列表 this.todoList.push(response_result.data) // 可选:清空输入框 e.target.value = '' }) },
内容的提问来源于stack exchange,提问作者baydogan
相关产品推荐
相关产品推荐

