vue实现模糊搜索功能
实现模糊搜索的基本思路
在Vue中实现模糊搜索功能通常需要结合输入框的监听、数据处理和筛选逻辑。模糊搜索的核心是对比用户输入的关键词与目标数据,返回相似度较高的结果。
使用计算属性实现搜索
通过计算属性可以高效地实现模糊搜索功能,计算属性会根据依赖的数据自动更新结果。
<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: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Orange' }
]
}
},
computed: {
filteredItems() {
const query = this.searchQuery.toLowerCase()
return this.items.filter(item =>
item.name.toLowerCase().includes(query)
)
}
}
}
</script>
使用第三方库增强搜索能力
对于更复杂的模糊搜索需求,可以使用Fuse.js等专门的模糊搜索库,它们提供了更强大的匹配算法和配置选项。
import Fuse from 'fuse.js'
export default {
data() {
return {
searchQuery: '',
items: [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Orange' }
],
fuse: null
}
},
created() {
this.fuse = new Fuse(this.items, {
keys: ['name'],
includeScore: true,
threshold: 0.4
})
},
computed: {
filteredItems() {
if (!this.searchQuery) return this.items
return this.fuse.search(this.searchQuery).map(result => result.item)
}
}
}
添加防抖优化性能
频繁触发搜索会影响性能,可以通过防抖函数限制搜索频率。
import _ from 'lodash'
export default {
data() {
return {
searchQuery: '',
items: [...],
filteredItems: []
}
},
watch: {
searchQuery: _.debounce(function(newVal) {
this.filterItems(newVal)
}, 300)
},
methods: {
filterItems(query) {
if (!query) {
this.filteredItems = this.items
return
}
const lowerQuery = query.toLowerCase()
this.filteredItems = this.items.filter(item =>
item.name.toLowerCase().includes(lowerQuery)
)
}
}
}
实现高亮显示匹配文本
为提升用户体验,可以在搜索结果中高亮显示匹配的文本部分。
<template>
<div>
<input v-model="searchQuery" placeholder="搜索...">
<ul>
<li v-for="item in filteredItems" :key="item.id" v-html="highlight(item.name)">
</li>
</ul>
</div>
</template>
<script>
export default {
methods: {
highlight(text) {
if (!this.searchQuery) return text
const regex = new RegExp(this.searchQuery, 'gi')
return text.replace(regex, match => `<span class="highlight">${match}</span>`)
}
}
}
</script>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
结合路由参数实现可分享搜索
如果需要保留搜索状态,可以将搜索参数同步到URL路由中。
export default {
watch: {
searchQuery(newVal) {
this.$router.push({
query: {
q: newVal
}
})
}
},
created() {
if (this.$route.query.q) {
this.searchQuery = this.$route.query.q
}
}
}






