vue实现搜索筛选
实现搜索筛选的基本思路
在Vue中实现搜索筛选功能通常涉及以下几个核心步骤:监听用户输入、过滤数据列表、实时更新视图。以下是具体实现方法。
使用计算属性过滤数据
计算属性是Vue中实现数据筛选的高效方式,能自动缓存结果并响应依赖变化。

<template>
<input v-model="searchQuery" placeholder="搜索...">
<ul>
<li v-for="item in filteredItems" :key="item.id">{{ item.name }}</li>
</ul>
</template>
<script>
export default {
data() {
return {
searchQuery: '',
items: [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Cherry' }
]
}
},
computed: {
filteredItems() {
return this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
}
}
</script>
使用watch实现异步搜索
当需要从API异步获取搜索结果时,watch配合防抖函数更合适。
<script>
import _ from 'lodash';
export default {
data() {
return {
searchQuery: '',
items: [],
allItems: []
}
},
created() {
this.fetchItems();
},
watch: {
searchQuery: _.debounce(function(newVal) {
this.filterItems(newVal);
}, 300)
},
methods: {
fetchItems() {
// 模拟API请求
this.allItems = [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Cherry' }
];
this.items = [...this.allItems];
},
filterItems(query) {
this.items = this.allItems.filter(item =>
item.name.toLowerCase().includes(query.toLowerCase())
);
}
}
}
</script>
多条件筛选实现
对于需要多个筛选条件的场景,可以扩展计算属性逻辑。

<script>
export default {
data() {
return {
nameQuery: '',
categoryQuery: '',
items: [
{ id: 1, name: 'Apple', category: 'fruit' },
{ id: 2, name: 'Carrot', category: 'vegetable' }
]
}
},
computed: {
filteredItems() {
return this.items.filter(item => {
const nameMatch = item.name.toLowerCase().includes(
this.nameQuery.toLowerCase()
);
const categoryMatch = item.category.includes(
this.categoryQuery
);
return nameMatch && categoryMatch;
});
}
}
}
</script>
使用第三方库增强搜索
对于复杂搜索需求,可以考虑使用Fuse.js等模糊搜索库。
import Fuse from 'fuse.js';
// 在组件中
methods: {
initFuse() {
const options = {
keys: ['name', 'category'],
threshold: 0.4
};
this.fuse = new Fuse(this.allItems, options);
},
searchWithFuse(query) {
this.items = query ? this.fuse.search(query).map(r => r.item) : [...this.allItems];
}
}
性能优化技巧
对于大型数据集,考虑以下优化手段:
- 使用虚拟滚动(vue-virtual-scroller)避免渲染大量DOM
- Web Worker处理密集型计算
- 分页加载搜索结果
- 防抖/节流控制搜索频率
// 分页示例
computed: {
paginatedItems() {
const start = (this.currentPage - 1) * this.pageSize;
return this.filteredItems.slice(start, start + this.pageSize);
}
}
以上方法可以根据具体需求组合使用,构建出灵活高效的搜索筛选功能。






