vue实现模糊
Vue实现模糊搜索的方法
在Vue中实现模糊搜索功能,可以通过多种方式实现。以下是几种常见的方法:
使用JavaScript原生方法
通过JavaScript的filter()和includes()方法实现简单模糊搜索:
data() {
return {
searchQuery: '',
items: ['apple', 'banana', 'orange', 'grape']
}
},
computed: {
filteredItems() {
return this.items.filter(item =>
item.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
}
使用第三方库Fuse.js
Fuse.js是一个强大的模糊搜索库,支持更复杂的搜索逻辑:
import Fuse from 'fuse.js'
data() {
return {
fuse: null,
searchQuery: '',
items: [
{ title: 'Old Man\'s War', author: 'John Scalzi' },
{ title: 'The Lock Artist', author: 'Steve Hamilton' }
]
}
},
created() {
this.fuse = new Fuse(this.items, {
keys: ['title', 'author'],
threshold: 0.4
})
},
computed: {
searchResults() {
return this.searchQuery
? this.fuse.search(this.searchQuery).map(r => r.item)
: this.items
}
}
使用Vue的v-for和计算属性
结合Vue的响应式特性,实现实时搜索:
<template>
<div>
<input v-model="searchQuery" placeholder="Search...">
<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: 'John' },
{ id: 2, name: 'Jane' }
]
}
},
computed: {
filteredItems() {
const query = this.searchQuery.toLowerCase()
return this.items.filter(item =>
item.name.toLowerCase().includes(query)
)
}
}
}
</script>
使用正则表达式实现高级搜索
通过正则表达式实现更灵活的模糊匹配:
computed: {
filteredItems() {
if (!this.searchQuery) return this.items
const pattern = new RegExp(
this.searchQuery
.split('')
.map(c => c.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
.join('.*'),
'i'
)
return this.items.filter(item => pattern.test(item.name))
}
}
结合debounce优化性能
对于大数据集,可以添加debounce减少计算频率:

import { debounce } from 'lodash'
methods: {
search: debounce(function() {
// 搜索逻辑
}, 300)
}
每种方法适用于不同场景,简单搜索可以使用原生JavaScript方法,复杂需求建议使用Fuse.js等专业库。实现时需考虑性能优化,特别是处理大量数据时。






