vue实现模糊查询功能
实现模糊查询的基本思路
在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: '苹果' },
{ id: 2, name: '香蕉' },
{ id: 3, name: '橙子' }
]
}
},
computed: {
filteredItems() {
return this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
}
}
</script>
使用第三方库实现更强大模糊查询
对于更复杂的模糊查询需求,可以使用Fuse.js等专业模糊搜索库。

安装Fuse.js:
npm install fuse.js
在Vue组件中使用:

<template>
<!-- 同上 -->
</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'],
threshold: 0.4
})
},
computed: {
filteredItems() {
if (!this.searchQuery) return this.items
return this.fuse.search(this.searchQuery).map(result => result.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() {
return this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase()) ||
item.description.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
}
高亮显示匹配内容
在显示搜索结果时,可以高亮匹配的部分文本。
<template>
<div v-html="highlight(item.name)"></div>
</template>
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>`)
}
}
通过以上方法,可以在Vue应用中实现灵活高效的模糊查询功能,根据实际需求选择简单实现或专业库方案。






