vue实现筛选列表
实现筛选列表的基本思路
在Vue中实现筛选列表通常需要结合数据绑定、计算属性和方法。通过监听用户输入或选择的变化,动态过滤原始数据列表,展示符合条件的项目。
准备数据源
定义一个数组作为原始数据源,包含需要筛选的列表项。每个列表项可以是对象,包含多个属性用于不同维度的筛选。
data() {
return {
items: [
{ id: 1, name: 'Apple', category: 'Fruit', price: 2.5 },
{ id: 2, name: 'Banana', category: 'Fruit', price: 1.2 },
{ id: 3, name: 'Carrot', category: 'Vegetable', price: 0.8 },
{ id: 4, name: 'Milk', category: 'Dairy', price: 3.5 }
],
searchTerm: '',
selectedCategory: ''
}
}
创建筛选逻辑
使用计算属性实现筛选逻辑,根据用户输入的条件返回过滤后的列表。计算属性会自动缓存结果,提高性能。
computed: {
filteredItems() {
return this.items.filter(item => {
const matchesSearch = item.name.toLowerCase().includes(this.searchTerm.toLowerCase())
const matchesCategory = !this.selectedCategory || item.category === this.selectedCategory
return matchesSearch && matchesCategory
})
}
}
添加用户输入界面
在模板中添加输入控件,让用户可以输入搜索词和选择分类。使用v-model实现双向数据绑定。
<div>
<input type="text" v-model="searchTerm" placeholder="Search items...">
<select v-model="selectedCategory">
<option value="">All Categories</option>
<option v-for="category in uniqueCategories" :value="category">
{{ category }}
</option>
</select>
</div>
显示筛选结果
使用v-for指令循环渲染过滤后的列表项。可以添加条件判断,当没有匹配结果时显示提示信息。
<ul>
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }} - {{ item.category }} - ${{ item.price }}
</li>
<li v-if="filteredItems.length === 0">No items match your criteria</li>
</ul>
添加分类选项
创建一个计算属性获取所有唯一的分类选项,用于下拉选择框。
computed: {
uniqueCategories() {
return [...new Set(this.items.map(item => item.category))]
}
}
多条件筛选扩展
对于更复杂的筛选需求,可以添加更多筛选条件和逻辑。例如增加价格范围筛选。
data() {
return {
minPrice: 0,
maxPrice: 100
}
}
computed: {
filteredItems() {
return this.items.filter(item => {
const matchesSearch = item.name.toLowerCase().includes(this.searchTerm.toLowerCase())
const matchesCategory = !this.selectedCategory || item.category === this.selectedCategory
const matchesPrice = item.price >= this.minPrice && item.price <= this.maxPrice
return matchesSearch && matchesCategory && matchesPrice
})
}
}
性能优化建议
对于大型列表,可以考虑以下优化措施:

- 使用debounce处理搜索输入
- 实现分页加载
- 使用虚拟滚动技术
- 将复杂计算移至Web Worker






