Vue中数组去重需用响应式更新:推荐splice(0, len, ...new Set(arr))或直接赋值(Vue 3/2.7+),Vue 2.6-需$set或splice;对象数组按字段去重后同样需响应式替换,禁用直接索引赋值或仅计算不更新。

在 Vue 中对数组去重后,必须确保响应式系统能检测到变化,否则视图不会更新。关键在于:不能直接修改原数组的内部元素(如用 arr[i] = newValue),而要使用 Vue 能追踪的数组变更方法,或用响应式替换。
✅ 使用 Vue 识别的数组变异方法(推荐)
Vue 重写了 push、pop、shift、unshift、splice、sort、reverse 这些方法,调用它们会触发更新。但注意:去重本身不是变异操作,所以需先计算新数组,再用 splice(0, length, ...newArray) 替换原内容:
-
正确示例:
this.list.splice(0, this.list.length, ...[...new Set(this.list)]) - 等价写法(更清晰):
this.list = [...new Set(this.list)]—— 这是赋值,Vue 3 和 Vue 2.7+ 支持;Vue 2.6 及更早需配合this.$set或用splice
✅ Vue 2 中兼容老版本的稳妥写法
Vue 2.6 以下版本对直接赋值 this.arr = newArr 的响应式支持有限(尤其当数组是对象属性时),建议:
- 用
this.$set(this, 'list', [...new Set(this.list)])(适用于根级响应式属性) - 或用
this.list.splice(0, this.list.length, ...new Set(this.list))(兼容所有 Vue 2 版本) - 若
list是嵌套在对象里的(如this.data.items),则用:this.$set(this.data, 'items', [...new Set(this.data.items)])
✅ 处理对象数组去重(按字段)
单纯用 Set 对对象无效,需手动去重并保持响应式更新:
立即学习“Java免费学习笔记(深入)”;
- 先用
filter+findIndex去重(例如按id):
const unique = this.list.filter((item, index, arr) =><br> arr.findIndex(i => i.id === item.id) === index)
- 再用响应式方式更新:
this.list = unique(Vue 3 / Vue 2.7+)
或this.list.splice(0, this.list.length, ...unique)(全版本安全)
⚠️ 避免这些常见错误
-
不要直接改索引:
this.list[0] = newItem不会触发更新(除非是 Vue 2.7+/3 且启用了 Proxy) -
不要只用
filter或map计算却不赋值/替换,那只是生成新数组,没更新响应式数据 -
避免在模板中直接写
[...new Set(list)]—— 每次渲染都新建数组,影响性能且不响应式


















