vue实现模糊
Vue实现模糊搜索的方法
在Vue中实现模糊搜索功能,可以通过多种方式完成。以下是几种常见的方法:

使用JavaScript的filter和includes方法
<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() {
return this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
}
}
</script>
使用正则表达式实现更灵活的匹配
computed: {
filteredItems() {
const query = this.searchQuery.toLowerCase()
if (!query) return this.items
return this.items.filter(item => {
const regex = new RegExp(query, 'i')
return regex.test(item.name)
})
}
}
使用第三方库实现更强大的模糊搜索
-
安装fuse.js库:

npm install fuse.js -
在Vue组件中使用:
import Fuse from 'fuse.js'
export default { data() { return { searchQuery: '', items: [...], fuse: null } }, mounted() { this.fuse = new Fuse(this.items, { keys: ['name'], includeScore: true, threshold: 0.4 }) }, computed: { filteredItems() { if (!this.searchQuery) return this.items return this.fuse.search(this.searchQuery).map(result => result.item) } } }
#### 实现带有高亮显示的模糊搜索
```javascript
<template>
<div>
<input v-model="searchQuery" placeholder="搜索...">
<ul>
<li v-for="item in filteredItems" :key="item.id" v-html="highlight(item.name)">
</li>
</ul>
</div>
</template>
<script>
export default {
methods: {
highlight(text) {
if (!this.searchQuery) return text
const regex = new RegExp(this.searchQuery, 'gi')
return text.replace(regex, match => `<span class="highlight">${match}</span>`)
}
}
}
</script>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
实现多字段模糊搜索
computed: {
filteredItems() {
const query = this.searchQuery.toLowerCase()
if (!query) return this.items
return this.items.filter(item => {
return Object.values(item).some(value =>
String(value).toLowerCase().includes(query)
)
})
}
}
以上方法可以根据实际需求选择使用,简单搜索可以使用原生JavaScript方法,复杂场景可以考虑使用专门的模糊搜索库如fuse.js。






