Vue按部门分组嵌套表格点击删除按钮无法移除用户且无控制台报错
问题原因
Array.filter()是纯函数,仅返回过滤后的新数组,不会修改原数组,原代码执行过滤后未将结果赋值给对应变量,源数据没有发生任何变更。Array.slice()的入参应为数值类型的起止索引,传入用户对象属于无效调用,不会产生任何修改效果。- 遍历逻辑的回调参数与外层的
user入参重名,出现变量覆盖,会导致取值逻辑异常。 - 直接修改嵌套对象属性时,Vue2 可能无法监听到数据变更,不会触发视图重渲染。
- 额外小问题:表头
<thead>的<tr>只定义了2个<th>,但表格实际有3列(多了删除操作列),会出现表格列错位。
修复方案
1. 修正表头结构
<thead> <tr> <th>Name</th> <th>Job Title</th> <th>操作</th> </tr> </thead>
2. 重写removeUser方法
removeUser(user) { axios.delete(`/api/users/${user.id}/delete`).then(response => { const deletedId = response.data.id // 遍历所有部门 Object.keys(this.personnal).forEach(department => { // 过滤掉已删除的用户,得到新的用户列表 const updatedUsers = this.personnal[department].filter(u => u.id !== deletedId) // 用$set赋值保证响应式触发 this.$set(this.personnal, department, updatedUsers) }) }) }
内容的提问来源于stack exchange,提问作者Aurilie
相关产品推荐
相关产品推荐

