vue 实现筛选功能
实现筛选功能的基本思路
在Vue中实现筛选功能通常涉及以下几个核心步骤:数据绑定、筛选逻辑处理、结果展示。以下是具体实现方法。
数据准备
准备需要筛选的数据源,通常是一个数组,可以存储在Vue组件的data中。
data() {
return {
items: [
{ id: 1, name: 'Apple', category: 'Fruit' },
{ id: 2, name: 'Banana', category: 'Fruit' },
{ id: 3, name: 'Carrot', category: 'Vegetable' }
],
filterText: '',
filterCategory: ''
}
}
输入绑定
使用v-model绑定输入框或下拉菜单的值,用于捕获用户的筛选条件。
<input v-model="filterText" placeholder="Search by name">
<select v-model="filterCategory">
<option value="">All Categories</option>
<option value="Fruit">Fruit</option>
<option value="Vegetable">Vegetable</option>
</select>
计算属性处理筛选逻辑
通过计算属性computed动态计算筛选后的结果,避免直接修改原始数据。
computed: {
filteredItems() {
return this.items.filter(item => {
const matchesText = item.name.toLowerCase().includes(this.filterText.toLowerCase())
const matchesCategory = this.filterCategory === '' || item.category === this.filterCategory
return matchesText && matchesCategory
})
}
}
展示筛选结果
使用v-for遍历计算属性filteredItems的结果,动态渲染筛选后的列表。
<ul>
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }} ({{ item.category }})
</li>
</ul>
多条件筛选扩展
若需支持更多筛选条件,只需在计算属性中增加逻辑即可。例如添加价格范围筛选:
data() {
return {
// ...其他数据
minPrice: 0,
maxPrice: 100
}
},
computed: {
filteredItems() {
return this.items.filter(item => {
const matchesText = item.name.toLowerCase().includes(this.filterText.toLowerCase())
const matchesCategory = this.filterCategory === '' || item.category === this.filterCategory
const matchesPrice = item.price >= this.minPrice && item.price <= this.maxPrice
return matchesText && matchesCategory && matchesPrice
})
}
}
使用第三方库优化性能
对于大型数据集,可使用lodash的_.debounce函数减少频繁触发筛选的频率。
import { debounce } from 'lodash'
methods: {
handleFilter: debounce(function() {
// 筛选逻辑
}, 300)
}
服务端筛选的实现
当数据量非常大时,可将筛选逻辑移至服务端,通过API传递参数并获取结果。
methods: {
async fetchFilteredItems() {
const response = await axios.get('/api/items', {
params: {
search: this.filterText,
category: this.filterCategory
}
})
this.filteredItems = response.data
}
}
注意事项
- 计算属性依赖的数据变化时会自动重新计算,无需手动触发。
- 若筛选条件复杂,可将逻辑拆分为多个计算属性以提高可读性。
- 对于嵌套数据结构的筛选,可能需要使用递归或深层比较。







