vue实现筛选列表
实现筛选列表的基本思路
在Vue中实现筛选列表功能,主要涉及数据绑定、计算属性和事件处理。通过v-model绑定筛选条件,利用计算属性动态过滤列表数据。
基础实现方法
创建Vue实例,定义原始数据列表和筛选条件。使用计算属性返回过滤后的列表。

new Vue({
el: '#app',
data: {
searchText: '',
items: [
{ id: 1, name: 'Apple', category: 'Fruit' },
{ id: 2, name: 'Carrot', category: 'Vegetable' },
{ id: 3, name: 'Banana', category: 'Fruit' }
]
},
computed: {
filteredItems() {
return this.items.filter(item =>
item.name.toLowerCase().includes(this.searchText.toLowerCase())
)
}
}
})
模板部分实现
在模板中使用v-model绑定搜索输入框,v-for渲染过滤后的列表。

<div id="app">
<input v-model="searchText" placeholder="Search...">
<ul>
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }} - {{ item.category }}
</li>
</ul>
</div>
多条件筛选实现
扩展筛选功能,支持按多个条件过滤。添加额外的筛选控件和数据属性。
data: {
searchText: '',
selectedCategory: '',
categories: ['Fruit', 'Vegetable'],
items: [
// 原始数据
]
},
computed: {
filteredItems() {
return this.items.filter(item => {
const nameMatch = item.name.toLowerCase().includes(
this.searchText.toLowerCase()
)
const categoryMatch = !this.selectedCategory ||
item.category === this.selectedCategory
return nameMatch && categoryMatch
})
}
}
模板中添加分类筛选
<select v-model="selectedCategory">
<option value="">All Categories</option>
<option v-for="category in categories" :value="category">
{{ category }}
</option>
</select>
性能优化建议
对于大型列表,考虑以下优化措施:
- 使用debounce处理输入事件,减少频繁过滤
- 添加分页功能,限制每次渲染的条目数量
- 考虑使用Web Worker进行繁重的计算
- 对于静态数据,可以预先建立索引
完整示例代码
<div id="app">
<input v-model="searchText" placeholder="Search by name...">
<select v-model="selectedCategory">
<option value="">All Categories</option>
<option v-for="category in categories" :value="category">
{{ category }}
</option>
</select>
<ul>
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }} ({{ item.category }})
</li>
</ul>
</div>
<script>
new Vue({
el: '#app',
data: {
searchText: '',
selectedCategory: '',
categories: ['Fruit', 'Vegetable'],
items: [
{ id: 1, name: 'Apple', category: 'Fruit' },
{ id: 2, name: 'Carrot', category: 'Vegetable' },
{ id: 3, name: 'Banana', category: 'Fruit' },
{ id: 4, name: 'Broccoli', category: 'Vegetable' }
]
},
computed: {
filteredItems() {
return this.items.filter(item => {
const nameMatch = item.name.toLowerCase().includes(
this.searchText.toLowerCase()
)
const categoryMatch = !this.selectedCategory ||
item.category === this.selectedCategory
return nameMatch && categoryMatch
})
}
}
})
</script>
注意事项
- 确保为列表项设置唯一的key属性
- 考虑空状态的处理,当没有匹配项时显示友好提示
- 对于复杂筛选逻辑,可以考虑将过滤函数拆分为单独的方法
- 在Vue 3中使用组合式API时,可以将筛选逻辑封装为可复用的composable






