vue实现搜索栏
实现搜索栏的基本结构
在Vue中创建一个搜索栏通常需要结合v-model实现双向数据绑定,监听用户输入。以下是一个基础模板示例:
<template>
<div class="search-container">
<input
type="text"
v-model="searchQuery"
placeholder="输入关键词..."
@keyup.enter="handleSearch"
/>
<button @click="handleSearch">搜索</button>
</div>
</template>
<script>
export default {
data() {
return {
searchQuery: ''
}
},
methods: {
handleSearch() {
this.$emit('search', this.searchQuery)
}
}
}
</script>
添加防抖优化
频繁触发搜索可能影响性能,可以通过防抖(debounce)优化:

import { debounce } from 'lodash'
export default {
data() {
return {
searchQuery: '',
debouncedSearch: debounce(this.emitSearch, 500)
}
},
methods: {
emitSearch() {
this.$emit('search', this.searchQuery)
},
handleInput() {
this.debouncedSearch()
}
}
}
结合列表过滤
若需实时过滤本地数据,可使用计算属性:

computed: {
filteredItems() {
return this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
}
集成第三方API
调用远程搜索接口时建议使用异步处理:
methods: {
async handleSearch() {
try {
const response = await axios.get('/api/search', {
params: { q: this.searchQuery }
})
this.results = response.data
} catch (error) {
console.error(error)
}
}
}
样式增强建议
添加基础CSS提升用户体验:
.search-container {
display: flex;
gap: 8px;
max-width: 400px;
}
input {
flex: 1;
padding: 8px 12px;
border: 1px solid #ddd;
border-radius: 4px;
}
button {
padding: 8px 16px;
background: #42b983;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
完整组件示例
<template>
<div class="search-box">
<input
v-model="searchTerm"
@input="onSearch"
placeholder="Search..."
/>
<ul v-if="showSuggestions && suggestions.length">
<li
v-for="item in suggestions"
@click="selectSuggestion(item)"
>
{{ item }}
</li>
</ul>
</div>
</template>
<script>
export default {
props: ['items'],
data() {
return {
searchTerm: '',
suggestions: [],
showSuggestions: false
}
},
methods: {
onSearch() {
if (this.searchTerm.length > 2) {
this.suggestions = this.items.filter(item =>
item.includes(this.searchTerm)
)
this.showSuggestions = true
} else {
this.suggestions = []
}
},
selectSuggestion(item) {
this.searchTerm = item
this.showSuggestions = false
this.$emit('search', item)
}
}
}
</script>






