vue实现模糊查找
Vue实现模糊查找的方法
使用计算属性实现
在Vue中可以通过计算属性结合JavaScript的filter和includes方法实现模糊查找。定义一个搜索关键词searchTerm,通过计算属性过滤数组。
data() {
return {
searchTerm: '',
items: ['apple', 'banana', 'orange', 'grape']
}
},
computed: {
filteredItems() {
return this.items.filter(item =>
item.toLowerCase().includes(this.searchTerm.toLowerCase())
)
}
}
使用第三方库Fuse.js
Fuse.js是一个强大的模糊搜索库,支持更复杂的搜索逻辑,如模糊匹配、权重设置等。首先安装Fuse.js:
npm install fuse.js
然后在Vue组件中使用:
import Fuse from 'fuse.js'
data() {
return {
searchTerm: '',
items: [
{ name: 'apple', price: 1 },
{ name: 'banana', price: 2 }
],
fuse: null
}
},
created() {
this.fuse = new Fuse(this.items, {
keys: ['name'],
threshold: 0.4
})
},
computed: {
searchResults() {
return this.searchTerm
? this.fuse.search(this.searchTerm).map(r => r.item)
: this.items
}
}
使用v-model和watch实现
对于需要更复杂逻辑的场景,可以使用watch监听搜索词变化:
data() {
return {
searchTerm: '',
items: ['apple', 'banana'],
filteredItems: []
}
},
watch: {
searchTerm(newVal) {
this.filteredItems = this.items.filter(item =>
item.toLowerCase().includes(newVal.toLowerCase())
)
}
},
created() {
this.filteredItems = [...this.items]
}
实现带有高亮显示的搜索
在搜索结果中高亮显示匹配部分,可以使用自定义过滤器或方法:
methods: {
highlight(text) {
if (!this.searchTerm) return text
const regex = new RegExp(`(${this.searchTerm})`, 'gi')
return text.replace(regex, '<span class="highlight">$1</span>')
}
}
模板中使用v-html绑定:
<div v-for="item in filteredItems" v-html="highlight(item)"></div>
使用lodash的防抖优化性能
对于大数据量或频繁输入的情况,可以使用lodash的debounce优化性能:

import { debounce } from 'lodash'
methods: {
search: debounce(function() {
// 搜索逻辑
}, 500)
}
注意事项
- 对于中文搜索,确保正确处理Unicode字符
- 考虑性能优化,特别是大数据量时的搜索效率
- 移动端输入时,考虑添加防抖或节流
- 对于复杂数据结构,可能需要嵌套搜索或多字段搜索






