过滤器不能用于数组去重,因其只接收单个值、无响应式追踪且小程序不支持;应使用computed、methods或工具函数在数据层处理。

过滤器(filters)不能用于去重——它只在模板插值和 v-bind 中生效,且不接收数组本身作为输入,更无法修改数据结构。想对列表去重,必须在数据层处理,而不是靠过滤器。
为什么不能用过滤器做数组去重
过滤器函数签名固定为 filter(value, ...args),它接收的是单个值(比如 {{ item | unique }}),不是整个数组;你没法在过滤器里遍历、比对、筛掉重复项。即使强行写,也会出现:
- 模板中写
{{ list | uniqueFilter }}—— 但uniqueFilter收到的list是原始引用,返回新数组后,Vue 2 不会自动更新视图(无响应式追踪) - 过滤器无法监听
list的变化,也不会在list推送新项时重新执行 - 小程序平台压根不支持自定义过滤器,该写法在微信/支付宝小程序里直接失效
真正可用的去重方式:用 computed 或 methods
把去重逻辑提前到响应式计算阶段,确保结果可追踪、可复用、跨平台一致。
- 按字段去重(如
id):computed: { uniqueList() { const seen = new Set() return this.rawList.filter(item => { const key = item.id + '' if (seen.has(key)) return false seen.add(key) return true }) } } - 对象深比较去重(小数据量适用):
computed: { uniqueList() { return this.rawList.filter((item, index, arr) => index === arr.findIndex(i => JSON.stringify(i) === JSON.stringify(item)) ) } }注意:JSON.stringify对函数、undefined、循环引用会出错,仅限简单对象 - 需要频繁增删时,改用方法封装(避免 computed 缓存干扰):
methods: { getUniqueList(list, key = 'id') { const seen = new Set() return list.filter(item => { const val = item[key] if (seen.has(val)) return false seen.add(val) return true }) } } // 模板中调用: // <view v-for="item in getUniqueList(rawList)" :key="item.id"></view>
大数据量或复杂结构怎么办
如果 rawList 超过 500 条,或去重逻辑涉及嵌套属性、异步映射(如 ID → 名称)、服务端分页等,别在每次渲染时都跑一遍 filter:
- 在
onLoad或请求回调里一次性去重并赋值:this.uniqueList = this.removeDuplicates(this.rawList, 'id')
- 把去重工具提成独立函数(非 Vue 依赖),放在
utils/array.js:export function uniqBy(arr, key) { if (!Array.isArray(arr)) return [] const seen = new Set() return arr.filter(item => { const val = typeof key === 'function' ? key(item) : item[key] if (seen.has(val)) return false seen.add(val) return true }) }然后在页面中import { uniqBy } from '@/utils/array' - 慎用
Set+map组合:它只适合扁平数组,对对象数组无效,除非你先map出id数组再查重,但会丢失原对象结构
最容易被忽略的是:去重不是目的,保证后续操作(如多选、编辑、提交)仍能正确映射到原始数据才是关键。所以别在 computed 里直接返回新数组就完事——得确认 uniqueList 中每个 item 仍是响应式对象,且其 id 等字段没被意外覆盖或转义。











