在 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
<p>注意:如果价格范围可能为空(比如初始为 <code>null</code> 或 <code>undefined</code>),可加安全判断避免报错:</p>
<pre class="brush:php;toolbar:false;">const filteredCount = computed(() => {
const min = minPrice.value ?? -Infinity;
const max = maxPrice.value ?? Infinity;
return products.value.filter(p => p.price >= min && p.price
<h3>模板中直接使用计算结果</h3>
<p>在模板里像普通响应式值一样使用,无需额外调用或解包:</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill9767" title="vue-admin-change-reviewer"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20e695c2374.jpg" alt="vue-admin-change-reviewer" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill9767" title="vue-admin-change-reviewer" class="overflowclass">vue-admin-change-reviewer</a>
<p class="overflowclass">审查 Vue 管理后台的变更请求(Vue 2 + Element UI,Vue 3 + Element Plus)。重点关注最小化变更实现、上线风险检查以及回归检查清单生成。</p>
</div>
<a rel="nofollow" href="/xiazai/skill9767" title="vue-admin-change-reviewer" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>
<pre class="brush:php;toolbar:false;"><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 filteredProducts.value.length);
这样既保持逻辑清晰,又提升性能(尤其商品量大时)。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!









