vue实现模糊查询
Vue 实现模糊查询的方法
在 Vue 中实现模糊查询可以通过多种方式完成,以下是几种常见的方法:
使用 JavaScript 的 filter 和 includes 方法
通过 Vue 的 computed 属性结合数组的 filter 方法实现模糊查询:
<template>
<div>
<input v-model="searchQuery" placeholder="搜索..." />
<ul>
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
searchQuery: '',
items: [
{ id: 1, name: '苹果' },
{ id: 2, name: '香蕉' },
{ id: 3, name: '橙子' },
],
};
},
computed: {
filteredItems() {
return this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
);
},
},
};
</script>
使用正则表达式实现更灵活的匹配
如果需要更复杂的模糊匹配,可以使用正则表达式:

computed: {
filteredItems() {
const query = this.searchQuery.toLowerCase();
return this.items.filter(item => {
const regex = new RegExp(query, 'i');
return regex.test(item.name);
});
},
},
使用第三方库(如 Fuse.js)
对于大型数据集或更高级的模糊搜索功能,可以使用 Fuse.js:
-
安装 Fuse.js:

npm install fuse.js -
在 Vue 组件中使用:
<template> <div> <input v-model="searchQuery" placeholder="搜索..." /> <ul> <li v-for="result in searchResults" :key="result.item.id"> {{ result.item.name }} </li> </ul> </div> </template>
export default { data() { return { searchQuery: '', items: [ { id: 1, name: '苹果' }, { id: 2, name: '香蕉' }, { id: 3, name: '橙子' }, ], fuse: null, }; }, created() { this.fuse = new Fuse(this.items, { keys: ['name'], threshold: 0.3, }); }, computed: { searchResults() { return this.searchQuery ? this.fuse.search(this.searchQuery) : this.items.map(item => ({ item })); }, }, };
```结合后端 API 实现模糊查询
如果数据量较大,可以将模糊查询逻辑放在后端:
methods: {
async searchItems() {
const response = await axios.get('/api/items', {
params: {
query: this.searchQuery,
},
});
this.filteredItems = response.data;
},
},
注意事项
- 对于中文搜索,可能需要额外处理拼音或分词。
- 性能优化:对于大型数据集,建议使用防抖(debounce)减少频繁搜索。
- 用户体验:可以添加加载状态和空结果提示。
以上方法可以根据实际需求选择或组合使用,以实现最佳的模糊查询效果。






