用 computed 实现多维过滤需统一响应式逻辑,支持关键词、分类、状态、价格等条件动态跳过与守卫判断,结合空值优化、排序及性能兜底,避免副作用。

用 computed 实现列表多维度过滤,关键在于把所有筛选条件(关键词、分类、状态、价格区间等)统一纳入一个响应式计算逻辑中,让 Vue 自动追踪变化、缓存结果、按需更新——不手动调用,不额外 watch,结构清晰且性能可控。
多条件组合过滤:每个参数都支持“未启用”跳过
用户可能只选分类、或只输关键词、或三者都填。计算属性里要避免硬性匹配,而是为每项加守卫判断:
- 关键词为空时,不执行 includes 判断;用 !this.searchKey.trim() 检查空白
- 分类 ID 为 null/0/undefined 时,跳过 category 匹配;写成 !this.selectedCat || item.categoryId === this.selectedCat
- 状态字段同理,用 !this.statusFilter || item.status === this.statusFilter
- 价格范围需转数字比对:(!this.priceRange.min || item.price >= +this.priceRange.min) && (!this.priceRange.max || item.price
多字段模糊搜索:统一转小写 + 可选链防错
用户搜“air”,应匹配 name、brand、sku、甚至 shortDesc。字段可能为 undefined,需安全访问:
- 用可选链 item.name?.toLowerCase().includes(key) 避免报错
- 多个字段用 || 连接,任意一个命中即保留该条目
- 关键词统一转小写:const key = this.searchKey.toLowerCase().trim()
- 示例完整条件:item.name?.toLowerCase().includes(key) || item.brand?.toLowerCase().includes(key) || item.sku?.includes(key)
过滤后立即排序:链式调用 .sort(),不拆分成两个 computed
先筛再排,一气呵成。在同一个 computed 中完成,避免中间数组被重复创建:
- 返回语句末尾直接接 .sort((a, b) => {...})
- 按销量降序:a.sales - b.sales
- 按价格升序:a.price - b.price
- 支持动态排序字段:if (this.sortBy === 'price') return a.price - b.price
空搜索优化与性能兜底
避免无意义运算,尤其在大数据量下提升响应感:
- 搜索词为空或全空白时,直接返回原数组引用:if (!this.searchKey.trim() && !Object.values(this.filters).some(v => v)) return this.rawList
- 万级列表建议配合 v-memo(Vue 3.2+),减少子组件重渲染
- 不建议在 computed 内做防抖或节流——那是事件处理器的事;computed 只管“变了就重算”
- 复杂逻辑可抽成纯函数(如 matchItem(item, filters)),但别在 computed 里触发副作用(如 console、API 调用)










