vue模糊查询实现
实现 Vue 模糊查询的方法
使用计算属性实现模糊查询
在 Vue 中,可以利用计算属性和 JavaScript 的 filter 方法实现模糊查询。首先需要准备数据源和搜索关键词。
data() {
return {
searchText: '',
items: [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Orange' }
]
}
},
computed: {
filteredItems() {
if (!this.searchText) return this.items
return this.items.filter(item =>
item.name.toLowerCase().includes(this.searchText.toLowerCase())
)
}
}
在模板中使用 v-model 绑定搜索输入框,并展示过滤后的结果:
<input v-model="searchText" placeholder="Search...">
<ul>
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }}
</li>
</ul>
使用 Lodash 的防抖优化性能
对于大数据量或频繁输入的搜索,可以使用 Lodash 的 debounce 方法优化性能。

import { debounce } from 'lodash'
methods: {
search: debounce(function() {
// 搜索逻辑
}, 500)
}
实现多字段模糊查询
如果需要同时搜索多个字段,可以扩展过滤逻辑:
computed: {
filteredItems() {
if (!this.searchText) return this.items
const search = this.searchText.toLowerCase()
return this.items.filter(item =>
item.name.toLowerCase().includes(search) ||
item.description.toLowerCase().includes(search)
)
}
}
使用第三方库实现高级搜索
对于更复杂的搜索需求,可以考虑使用专门的搜索库如 Fuse.js:

import Fuse from 'fuse.js'
data() {
return {
fuse: null,
// 其他数据
}
},
created() {
this.fuse = new Fuse(this.items, {
keys: ['name', 'description'],
threshold: 0.4
})
},
computed: {
filteredItems() {
if (!this.searchText) return this.items
return this.fuse.search(this.searchText).map(result => result.item)
}
}
服务器端模糊查询
对于大量数据,建议将搜索逻辑放在服务器端:
methods: {
async searchItems() {
const response = await axios.get('/api/items', {
params: { q: this.searchText }
})
this.filteredItems = response.data
}
}
在输入框上添加事件监听:
<input
v-model="searchText"
@input="searchItems"
placeholder="Search...">
以上方法可以根据实际需求选择或组合使用,实现 Vue 中的模糊查询功能。






