computed 实现列表搜索过滤的核心是将原始数据和搜索关键词作为响应式依赖,由 Vue 自动追踪并重新计算结果;支持多字段匹配、空值防护,无需防抖,配合 v-memo 和空搜索优化可提升万级列表性能。
用
computed
做列表搜索过滤,核心就一点:把“原始数据”和“搜索关键词”作为响应式依赖,让 Vue 自动追踪变化、重新计算过滤后结果——不用手动调用方法,也不用 watch 监听,简洁又高效。
基础写法:一个输入框 + computed 过滤
假设你有商品列表
,用户在
输入关键词:
在 data 中定义
在 computed 中写一个过滤后的列表,比如
模板里直接遍历
,而不是原始列表
示例代码:
computed: {filteredGoods() {return this.goodsList.filter(item =>item.name.toLowerCase().includes(this.searchKey.toLowerCase()));}}
支持多字段模糊匹配(标题、描述、分类)
用户搜“苹果”,可能想匹配商品名、副标题或所属分类。只需扩展 filter 条件:
用
连接多个字段的 includes 判断
统一转小写避免大小写敏感问题
加空值判断防止 item.desc 为 undefined 报错
例如:
item.name?.toLowerCase().includes(key) ||item.desc?.toLowerCase().includes(key) ||item.category?.toLowerCase().includes(key)
防抖不是 computed 的事,但得配合好
computed 本身是响应式计算,不处理输入频率。如果搜索接口要发请求,防抖放 input 的 @input 或 @keyup 里;但如果只是前端过滤,不需要防抖——Vue 的 computed 是惰性求值,输入频繁也不会重复执行,只有依赖变化且被模板引用时才更新。
纯前端过滤:直接用 computed,轻量无压力
需要调接口查后端:在 methods 里写防抖函数,搜索关键词变化后触发请求,再更新本地 list
两者混用常见场景:先 computed 过滤已有数据,再加个“搜不到?去全网找”按钮触发远程搜索
性能优化小技巧(万级列表也不卡)
列表超过 5000 条时,filter 可能有感知延迟。可加两层优化:
用
+
(Vue 3.2+):给 v-for 加 memo,跳过未变化项的重渲染
搜索为空时,直接返回原数组引用(避免无谓 filter)
复杂逻辑可抽成函数,但别在 computed 里做副作用(如 console.log、修改 data)
例如:
filteredGoods() {if (!this.searchKey.trim()) return this.goodsList;// 否则执行 filter}
goodsListsearchKeysearchKey: ''filteredGoodsfilteredGoods||computedv-memo