vue搜索功能如何实现
实现Vue搜索功能的方法
基础搜索功能实现
在Vue中实现搜索功能通常需要结合v-model和计算属性。创建一个输入框绑定到data属性,然后使用计算属性过滤列表数据。
<template>
<div>
<input v-model="searchQuery" placeholder="搜索...">
<ul>
<li v-for="item in filteredList" :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: {
filteredList() {
return this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
}
}
</script>
使用第三方库实现高级搜索
对于更复杂的搜索需求,可以使用Fuse.js等模糊搜索库。先安装Fuse.js:

npm install fuse.js
然后在Vue组件中使用:
import Fuse from 'fuse.js'
export default {
data() {
return {
searchQuery: '',
items: [...],
fuse: null
}
},
created() {
this.fuse = new Fuse(this.items, {
keys: ['name', 'description'],
threshold: 0.4
})
},
computed: {
filteredList() {
if (!this.searchQuery) return this.items
return this.fuse.search(this.searchQuery).map(result => result.item)
}
}
}
添加防抖优化性能
频繁触发搜索会影响性能,可以使用lodash的debounce函数:

import { debounce } from 'lodash'
export default {
data() {
return {
searchQuery: '',
filteredItems: []
}
},
watch: {
searchQuery: debounce(function(newVal) {
this.filteredItems = this.items.filter(item =>
item.name.toLowerCase().includes(newVal.toLowerCase())
)
}, 300)
}
}
服务器端搜索实现
对于大数据集,应该考虑服务器端搜索:
methods: {
async searchItems() {
try {
const response = await axios.get('/api/items', {
params: { q: this.searchQuery }
})
this.filteredItems = response.data
} catch (error) {
console.error(error)
}
}
},
watch: {
searchQuery() {
this.searchItems()
}
}
添加搜索建议功能
实现搜索建议可以提升用户体验:
<template>
<div>
<input
v-model="searchQuery"
@input="showSuggestions = true"
@blur="showSuggestions = false"
placeholder="搜索...">
<ul v-if="showSuggestions && suggestions.length">
<li
v-for="suggestion in suggestions"
:key="suggestion.id"
@click="selectSuggestion(suggestion)">
{{ suggestion.name }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
showSuggestions: false,
suggestions: []
}
},
watch: {
searchQuery(newVal) {
if (newVal.length > 1) {
this.suggestions = this.items.filter(item =>
item.name.toLowerCase().includes(newVal.toLowerCase())
).slice(0, 5)
} else {
this.suggestions = []
}
}
},
methods: {
selectSuggestion(item) {
this.searchQuery = item.name
this.showSuggestions = false
}
}
}
</script>






