使用vue实现模糊搜索
实现模糊搜索的基本思路
在Vue中实现模糊搜索通常需要结合输入框的监听、数据处理和过滤逻辑。模糊搜索的核心是对用户输入的关键词进行模糊匹配,返回相关结果。
安装依赖(可选)
如果需要更强大的模糊搜索功能,可以安装fuse.js库:
npm install fuse.js
基础实现方式
使用Vue的computed属性实现简单模糊搜索:

<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() {
const query = this.searchQuery.toLowerCase()
return this.items.filter(item =>
item.name.toLowerCase().includes(query)
)
}
}
}
</script>
使用Fuse.js实现高级模糊搜索
对于更复杂的模糊匹配需求,可以使用Fuse.js:
<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>
<script>
import Fuse from 'fuse.js'
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'],
includeScore: true,
threshold: 0.4
})
},
computed: {
searchResults() {
return this.searchQuery
? this.fuse.search(this.searchQuery)
: this.items.map(item => ({ item }))
}
}
}
</script>
优化搜索性能
对于大数据集,可以添加防抖功能减少频繁搜索带来的性能问题:

<script>
import _ from 'lodash'
export default {
data() {
return {
searchQuery: '',
items: [...], // 大量数据
filteredItems: []
}
},
watch: {
searchQuery: _.debounce(function(newVal) {
this.filteredItems = this.items.filter(item =>
item.name.toLowerCase().includes(newVal.toLowerCase())
)
}, 300)
}
}
</script>
多字段搜索实现
当需要搜索多个字段时,可以扩展过滤逻辑:
computed: {
filteredItems() {
const query = this.searchQuery.toLowerCase()
return this.items.filter(item =>
item.name.toLowerCase().includes(query) ||
item.description.toLowerCase().includes(query)
)
}
}
样式优化建议
为搜索结果添加高亮显示,提升用户体验:
<template>
<li v-for="item in filteredItems" :key="item.id">
<span v-html="highlight(item.name, searchQuery)"></span>
</li>
</template>
<script>
export default {
methods: {
highlight(text, query) {
if (!query) return text
const regex = new RegExp(query, 'gi')
return text.replace(regex, match => `<span class="highlight">${match}</span>`)
}
}
}
</script>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
这些方法可以根据实际项目需求进行组合和调整,实现适合不同场景的模糊搜索功能。






