vue模糊查询的实现
实现模糊查询的基本思路
在Vue中实现模糊查询通常涉及以下核心步骤:监听用户输入、过滤数据列表、动态渲染结果。以下是具体实现方法:
使用计算属性过滤数据
计算属性适合基于响应式数据自动更新的场景。假设有一个数据列表items和用户输入的查询关键词searchQuery:
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)
)
}
}
模板部分:
<input v-model="searchQuery" placeholder="Search...">
<ul>
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }}
</li>
</ul>
使用watch实现异步查询
当需要处理大量数据或异步操作时,可以使用watch配合防抖:
data() {
return {
searchQuery: '',
filteredItems: [],
allItems: [...]
}
},
watch: {
searchQuery: _.debounce(function(newVal) {
const query = newVal.toLowerCase()
this.filteredItems = this.allItems.filter(item =>
item.name.toLowerCase().includes(query)
)
}, 300)
}
支持多字段模糊查询
扩展过滤逻辑以支持对象多个字段的搜索:
computed: {
filteredItems() {
const query = this.searchQuery.toLowerCase()
return this.items.filter(item =>
Object.values(item).some(
val => String(val).toLowerCase().includes(query)
)
)
}
}
使用第三方库增强功能
对于更复杂的模糊匹配,可以使用Fuse.js等专业库:
import Fuse from 'fuse.js'
data() {
return {
fuse: null,
searchOptions: {
keys: ['name', 'description'],
threshold: 0.4
}
}
},
created() {
this.fuse = new Fuse(this.allItems, this.searchOptions)
},
methods: {
search() {
this.filteredItems = this.searchQuery
? this.fuse.search(this.searchQuery).map(r => r.item)
: this.allItems
}
}
性能优化建议
对于大型数据集,考虑以下优化措施:
- 使用Web Worker处理过滤计算
- 实现分页加载结果
- 对原始数据建立索引
- 添加加载状态指示器
样式增强示例
为搜索结果添加高亮显示:
methods: {
highlight(text) {
const query = this.searchQuery
if (!query) return text
return text.replace(
new RegExp(query, 'gi'),
match => `<span class="highlight">${match}</span>`
)
}
}
模板中使用v-html:
<li v-for="item in filteredItems" :key="item.id">
<span v-html="highlight(item.name)"></span>
</li>
CSS部分:
.highlight {
background-color: yellow;
font-weight: bold;
}
以上方法可根据具体需求组合使用,实现从简单到复杂的各种模糊查询场景。







