vue实现模糊
Vue实现模糊搜索的方法
在Vue中实现模糊搜索功能,可以通过以下步骤完成:
安装必要的依赖
如果需要更强大的模糊搜索功能,可以安装fuse.js库:

npm install fuse.js
基础实现(不使用库) 在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() {
const query = this.searchQuery.toLowerCase()
return this.items.filter(item =>
item.name.toLowerCase().includes(query)
)
}
}
}
</script>
使用Fuse.js实现更强大的模糊搜索

<template>
<div>
<input v-model="searchQuery" placeholder="搜索..." />
<ul>
<li v-for="result in searchResults" :key="result.item.id">
{{ result.item.name }}
</li>
</ul>
</div>
</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'],
includeScore: true,
threshold: 0.4
})
},
computed: {
searchResults() {
return this.searchQuery ? this.fuse.search(this.searchQuery) : this.items.map(item => ({ item }))
}
}
}
</script>
优化性能 对于大数据集,考虑添加防抖功能:
import _ from 'lodash'
export default {
data() {
return {
searchQuery: '',
filteredItems: []
}
},
watch: {
searchQuery: _.debounce(function(newVal) {
this.filterItems(newVal)
}, 300)
},
methods: {
filterItems(query) {
// 过滤逻辑
}
}
}
样式增强 可以添加高亮匹配部分的样式:
<template>
<li v-for="item in filteredItems" :key="item.id">
<span v-html="highlightMatches(item.name, searchQuery)"></span>
</li>
</template>
<script>
export default {
methods: {
highlightMatches(text, query) {
if (!query) return text
const regex = new RegExp(query, 'gi')
return text.replace(regex, match => `<span class="highlight">${match}</span>`)
}
}
}
</script>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
这些方法可以根据实际需求选择使用,简单场景可以使用基础实现,复杂场景推荐使用Fuse.js库。






