在 Vue 3 中,用 computed 实现价格区间过滤后的商品数量统计,核心是先基于 minPrice、maxPrice 响应式筛选 products,再取 length;需用 ref 声明价格范围并绑定表单,用 ref 或 reactive 管理商品列表,computed 内部 filter 并处理 null 边界,可选缓存 filteredProducts 提升性能。

在 Vue 3 中,用 computed 实现价格区间过滤后的商品数量统计,核心是:先基于当前价格范围筛选商品,再对筛选结果取 .length。关键在于让筛选逻辑响应式依赖价格范围变量(如 minPrice、maxPrice),并确保商品列表本身也是响应式的。
定义响应式的价格范围和商品列表
使用 ref 或 reactive 声明价格上下限及商品数据,这是 computed 能自动更新的前提:
-
minPrice和maxPrice推荐用ref,便于绑定表单输入(如<input v-model.number="minPrice">) - 商品列表(如
products)建议用ref包裹数组,或用reactive包裹对象(含products字段)
编写 computed 计算过滤后数量
在 setup() 中定义一个 computed,内部用 filter 筛选,再返回长度:
const filteredCount = computed(() => {
return products.value.filter(p =>
p.price >= minPrice.value &&
p.price <= maxPrice.value
).length;
});
注意:如果价格范围可能为空(比如初始为 null 或 undefined),可加安全判断避免报错:
立即学习“前端免费学习笔记(深入)”;
审查 Vue 管理后台的变更请求(Vue 2 + Element UI,Vue 3 + Element Plus)。重点关注最小化变更实现、上线风险检查以及回归检查清单生成。
const filteredCount = computed(() => {
const min = minPrice.value ?? -Infinity;
const max = maxPrice.value ?? Infinity;
return products.value.filter(p => p.price >= min && p.price <= max).length;
});
模板中直接使用计算结果
在模板里像普通响应式值一样使用,无需额外调用或解包:
<p>符合条件的商品共 {{ filteredCount }} 件</p>
只要 minPrice、maxPrice 或 products 中任一值变化,filteredCount 会自动重新计算。
进阶:复用筛选逻辑 + 支持空范围跳过过滤
若还需展示过滤后的商品列表(不只是数量),可拆出一个公共的 filteredProducts 计算属性,再从中读取数量,避免重复过滤:
const filteredProducts = computed(() => {
if (minPrice.value == null && maxPrice.value == null) return products.value;
return products.value.filter(p => {
const aboveMin = minPrice.value == null || p.price >= minPrice.value;
const belowMax = maxPrice.value == null || p.price <= maxPrice.value;
return aboveMin && belowMax;
});
});
const filteredCount = computed(() => filteredProducts.value.length);
这样既保持逻辑清晰,又提升性能(尤其商品量大时)。

















