使用vue实现搜索
实现搜索功能的基本步骤
在Vue中实现搜索功能,可以通过v-model绑定输入框,结合计算属性或方法对数据进行过滤。
模板部分
<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>
使用watch实现搜索
对于更复杂的搜索逻辑,可以使用watch来监听搜索词的变化。

<script>
export default {
data() {
return {
searchQuery: '',
items: [
{ id: 1, name: '苹果' },
{ id: 2, name: '香蕉' },
{ id: 3, name: '橙子' }
],
filteredItems: []
}
},
watch: {
searchQuery(newVal) {
this.filteredItems = this.items.filter(item =>
item.name.toLowerCase().includes(newVal.toLowerCase())
)
}
},
created() {
this.filteredItems = [...this.items]
}
}
</script>
异步搜索实现
当需要从API获取搜索结果时,可以使用异步方法。
<script>
export default {
data() {
return {
searchQuery: '',
searchResults: [],
isLoading: false
}
},
methods: {
async search() {
if (this.searchQuery.length < 2) return
this.isLoading = true
try {
const response = await fetch(`/api/search?q=${this.searchQuery}`)
this.searchResults = await response.json()
} catch (error) {
console.error('搜索出错:', error)
} finally {
this.isLoading = false
}
}
},
watch: {
searchQuery: {
handler: 'search',
immediate: false,
debounce: 300
}
}
}
</script>
使用第三方库实现高级搜索
对于更复杂的搜索需求,可以考虑使用第三方库如Fuse.js实现模糊搜索。
安装Fuse.js:

npm install fuse.js
使用示例:
<script>
import Fuse from 'fuse.js'
export default {
data() {
return {
searchQuery: '',
items: [
{ id: 1, name: '苹果', category: '水果' },
{ id: 2, name: '胡萝卜', category: '蔬菜' },
{ id: 3, name: '香蕉', category: '水果' }
],
fuse: null,
searchResults: []
}
},
created() {
const options = {
keys: ['name', 'category'],
threshold: 0.4
}
this.fuse = new Fuse(this.items, options)
},
watch: {
searchQuery(newVal) {
this.searchResults = newVal
? this.fuse.search(newVal).map(r => r.item)
: [...this.items]
}
}
}
</script>
搜索功能优化建议
添加防抖功能可以减少频繁搜索请求。可以使用lodash的debounce方法或Vue的watch选项。
import { debounce } from 'lodash'
export default {
methods: {
search: debounce(function() {
// 搜索逻辑
}, 300)
}
}
为搜索框添加加载状态和空状态提示可以提升用户体验。
<template>
<div>
<input
v-model="searchQuery"
placeholder="搜索..."
@input="onSearchInput"
>
<div v-if="isLoading">搜索中...</div>
<div v-else-if="searchResults.length === 0 && searchQuery">
没有找到匹配的结果
</div>
<ul v-else>
<li v-for="item in searchResults" :key="item.id">
{{ item.name }}
</li>
</ul>
</div>
</template>






