vue 实现模糊搜索
Vue 实现模糊搜索的方法
使用计算属性实现模糊搜索
在 Vue 中,可以通过计算属性结合 JavaScript 的 filter 和 includes 方法实现简单的模糊搜索功能。假设有一个数据列表 items 和一个搜索关键词 searchTerm:
data() {
return {
items: ['Apple', 'Banana', 'Orange', 'Grape'],
searchTerm: ''
}
},
computed: {
filteredItems() {
return this.items.filter(item =>
item.toLowerCase().includes(this.searchTerm.toLowerCase())
)
}
}
在模板中使用 v-model 绑定搜索框,并展示过滤后的结果:
<input v-model="searchTerm" placeholder="Search...">
<ul>
<li v-for="item in filteredItems" :key="item">{{ item }}</li>
</ul>
使用第三方库实现更强大的模糊搜索
对于更复杂的模糊搜索需求,可以使用 fuse.js 这样的专门库:
安装 fuse.js:

npm install fuse.js
在 Vue 组件中使用:
import Fuse from 'fuse.js'
data() {
return {
items: [
{ name: 'Apple', category: 'Fruit' },
{ name: 'Carrot', category: 'Vegetable' }
],
searchTerm: '',
fuse: null
}
},
created() {
this.fuse = new Fuse(this.items, {
keys: ['name', 'category'],
threshold: 0.4
})
},
computed: {
filteredItems() {
return this.searchTerm
? this.fuse.search(this.searchTerm).map(result => result.item)
: this.items
}
}
实现带高亮的模糊搜索
可以扩展模糊搜索功能,在结果中高亮匹配的部分:
methods: {
highlight(text, query) {
if (!query) return text
const regex = new RegExp(`(${query})`, 'gi')
return text.replace(regex, '<span class="highlight">$1</span>')
}
}
在模板中使用 v-html 渲染高亮内容:

<li v-for="item in filteredItems" :key="item.name">
<span v-html="highlight(item.name, searchTerm)"></span>
</li>
使用防抖优化搜索性能
对于大数据集,可以使用防抖技术减少频繁搜索带来的性能问题:
import { debounce } from 'lodash'
methods: {
debouncedSearch: debounce(function() {
// 执行搜索逻辑
}, 300)
}
服务端模糊搜索实现
当数据量很大时,可以考虑将模糊搜索逻辑移至服务端:
methods: {
async searchItems() {
const response = await axios.get('/api/items', {
params: { q: this.searchTerm }
})
this.filteredItems = response.data
}
}
多字段权重搜索
使用 fuse.js 可以设置不同字段的搜索权重:
this.fuse = new Fuse(this.items, {
keys: [
{ name: 'name', weight: 0.7 },
{ name: 'category', weight: 0.3 }
]
})
以上方法可以根据实际需求选择或组合使用,实现从简单到复杂的模糊搜索功能。






