vue实现列表的过滤
实现列表过滤的基本方法
在Vue中实现列表过滤通常涉及使用v-for指令结合计算属性或方法。通过计算属性可以高效地处理过滤逻辑,避免每次渲染都重新计算。
定义一个数据数组和一个过滤条件:
data() {
return {
items: [
{ id: 1, name: 'Apple', category: 'fruit' },
{ id: 2, name: 'Carrot', category: 'vegetable' },
{ id: 3, name: 'Banana', category: 'fruit' }
],
filterText: ''
}
}
使用计算属性实现过滤:

computed: {
filteredItems() {
return this.items.filter(item =>
item.name.toLowerCase().includes(this.filterText.toLowerCase())
)
}
}
结合输入框实时过滤
在模板中添加输入框绑定filterText,并使用v-for渲染过滤后的列表:
<input v-model="filterText" placeholder="Filter items...">
<ul>
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }} ({{ item.category }})
</li>
</ul>
多条件过滤实现
对于更复杂的过滤场景,可以扩展计算属性逻辑。例如按分类和名称同时过滤:

data() {
return {
filterCategory: ''
}
},
computed: {
filteredItems() {
return this.items.filter(item => {
const nameMatch = item.name.toLowerCase().includes(
this.filterText.toLowerCase()
)
const categoryMatch = this.filterCategory === '' ||
item.category === this.filterCategory
return nameMatch && categoryMatch
})
}
}
使用自定义过滤方法
如果过滤逻辑需要复用或更复杂,可以提取为独立方法:
methods: {
customFilter(items) {
// 自定义过滤逻辑
return items.filter(/*...*/)
}
},
computed: {
filteredItems() {
return this.customFilter(this.items)
}
}
性能优化技巧
对于大型列表,考虑以下优化:
- 使用
debounce对输入事件进行防抖处理 - 在过滤前确保数据已正确加载
- 对于固定选项可提前生成过滤后的副本
import { debounce } from 'lodash'
methods: {
handleFilter: debounce(function() {
// 过滤逻辑
}, 300)
}
服务端过滤结合
当数据量非常大时,考虑将过滤逻辑移至服务端:
methods: {
async fetchFilteredData() {
const response = await axios.get('/api/items', {
params: {
search: this.filterText
}
})
this.filteredData = response.data
}
},
watch: {
filterText() {
this.fetchFilteredData()
}
}






