vue实现商品筛选功能
实现商品筛选功能的步骤
数据结构设计
使用Vue的响应式数据存储商品列表和筛选条件
data() {
return {
products: [], // 商品列表
filters: {
category: '', // 分类筛选
priceRange: [0, 1000], // 价格区间
stockStatus: 'all' // 库存状态
}
}
}
计算属性实现筛选逻辑
通过计算属性动态返回筛选后的商品列表
computed: {
filteredProducts() {
return this.products.filter(product => {
const matchCategory = !this.filters.category ||
product.category === this.filters.category
const matchPrice = product.price >= this.filters.priceRange[0] &&
product.price <= this.filters.priceRange[1]
const matchStock = this.filters.stockStatus === 'all' ||
(this.filters.stockStatus === 'inStock' && product.stock > 0) ||
(this.filters.stockStatus === 'outStock' && product.stock === 0)
return matchCategory && matchPrice && matchStock
})
}
}
模板中的筛选控件
在模板中绑定筛选条件到表单元素

<div class="filter-section">
<select v-model="filters.category">
<option value="">所有分类</option>
<option v-for="cat in categories" :value="cat">{{cat}}</option>
</select>
<input type="range" v-model="filters.priceRange[0]" min="0" max="1000">
<input type="range" v-model="filters.priceRange[1]" min="0" max="1000">
<label>
<input type="radio" v-model="filters.stockStatus" value="all"> 全部
</label>
<label>
<input type="radio" v-model="filters.stockStatus" value="inStock"> 有货
</label>
</div>
渲染筛选结果
使用计算属性显示筛选结果
<div class="product-list">
<div v-for="product in filteredProducts" :key="product.id" class="product-item">
<h3>{{ product.name }}</h3>
<p>价格: {{ product.price }}</p>
<p>库存: {{ product.stock }}</p>
</div>
</div>
性能优化建议
对于大型商品列表,考虑以下优化措施:

- 使用虚拟滚动技术避免渲染过多DOM元素
- 对筛选条件变化添加防抖处理
- 复杂筛选条件可考虑使用Web Worker进行计算
组件化实现
将筛选功能拆分为独立组件提高复用性
Vue.component('product-filter', {
props: ['value'],
template: `
<div>
<select v-model="localFilters.category">
<!-- 筛选选项 -->
</select>
<!-- 其他筛选控件 -->
</div>
`,
computed: {
localFilters: {
get() { return this.value },
set(val) { this.$emit('input', val) }
}
}
})
服务端筛选实现
当商品数据量大时,可改为服务端筛选
methods: {
async applyFilters() {
const response = await axios.get('/api/products', {
params: this.filters
})
this.products = response.data
}
}
通过以上方法可以实现完整的商品筛选功能,根据项目需求可调整筛选条件和交互方式。






