vue实现分类筛选
Vue 实现分类筛选的方法
数据准备
在 Vue 组件中定义分类数据和筛选条件。通常使用 data 或 computed 属性管理数据。
data() {
return {
products: [
{ id: 1, name: 'Product A', category: 'Electronics', price: 200 },
{ id: 2, name: 'Product B', category: 'Clothing', price: 50 },
{ id: 3, name: 'Product C', category: 'Electronics', price: 150 }
],
selectedCategory: '',
priceRange: [0, 1000]
}
}
筛选逻辑实现
使用 computed 属性动态计算筛选结果,避免直接修改原始数据。
computed: {
filteredProducts() {
return this.products.filter(product => {
const matchesCategory =
!this.selectedCategory ||
product.category === this.selectedCategory
const matchesPrice =
product.price >= this.priceRange[0] &&
product.price <= this.priceRange[1]
return matchesCategory && matchesPrice
})
}
}
模板绑定
在模板中使用 v-model 绑定筛选条件,展示筛选结果。
<div>
<select v-model="selectedCategory">
<option value="">All Categories</option>
<option v-for="cat in categories" :value="cat">{{ cat }}</option>
</select>
<input type="range" v-model="priceRange[0]" min="0" max="1000">
<input type="range" v-model="priceRange[1]" min="0" max="1000">
<ul>
<li v-for="product in filteredProducts" :key="product.id">
{{ product.name }} - {{ product.category }} (${{ product.price }})
</li>
</ul>
</div>
动态分类列表
提取唯一分类列表作为计算属性,避免硬编码。
computed: {
categories() {
return [...new Set(this.products.map(p => p.category))]
}
}
多条件筛选扩展
对于更复杂的筛选需求,可以扩展筛选逻辑。
computed: {
filteredProducts() {
return this.products.filter(product => {
// 分类筛选
const categoryMatch =
!this.filters.category ||
product.category === this.filters.category
// 价格筛选
const priceMatch =
product.price >= this.filters.minPrice &&
product.price <= this.filters.maxPrice
// 搜索关键词筛选
const searchMatch =
!this.filters.search ||
product.name.toLowerCase().includes(this.filters.search.toLowerCase())
return categoryMatch && priceMatch && searchMatch
})
}
}
使用 Vuex 管理状态
对于大型应用,可以使用 Vuex 集中管理筛选状态。
// store.js
state: {
products: [...],
filters: {
category: '',
minPrice: 0,
maxPrice: 1000,
search: ''
}
},
getters: {
filteredProducts: state => {
return state.products.filter(product => {
// 筛选逻辑
})
}
}
性能优化
对于大数据量场景,可以考虑以下优化:
- 使用虚拟滚动只渲染可见项
- 添加防抖处理频繁的筛选操作
- 考虑分页加载数据
// 添加防抖
methods: {
applyFilters: _.debounce(function() {
this.filterChanged = true
}, 300)
}






