vue实现搜索组件
Vue 实现搜索组件的方法
基础搜索组件实现
创建一个基础搜索组件,包含输入框和搜索按钮。使用 v-model 绑定输入值,通过 @click 或 @keyup.enter 触发搜索。
<template>
<div class="search-container">
<input
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>
防抖优化
为避免频繁触发搜索请求,使用 Lodash 的 debounce 或手动实现防抖。

import { debounce } from 'lodash'
export default {
methods: {
handleSearch: debounce(function() {
this.$emit('search', this.searchQuery)
}, 500)
}
}
异步搜索与加载状态
添加加载状态提示,适用于异步搜索场景。
<template>
<div>
<input v-model="searchQuery" @input="handleInput" />
<span v-if="isLoading">搜索中...</span>
</div>
</template>
<script>
export default {
data() {
return {
isLoading: false,
searchQuery: ''
}
},
methods: {
async handleInput() {
this.isLoading = true
await this.$emit('search', this.searchQuery)
this.isLoading = false
}
}
}
</script>
搜索建议功能
实现输入时动态显示搜索建议列表。

<template>
<div class="search-suggestions">
<input v-model="searchQuery" @input="fetchSuggestions" />
<ul v-if="suggestions.length">
<li
v-for="(item, index) in suggestions"
:key="index"
@click="selectSuggestion(item)"
>
{{ item }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
searchQuery: '',
suggestions: []
}
},
methods: {
fetchSuggestions() {
// 调用API获取建议数据
this.suggestions = ['Vue', 'React', 'Angular'].filter(item =>
item.toLowerCase().includes(this.searchQuery.toLowerCase())
)
},
selectSuggestion(item) {
this.searchQuery = item
this.suggestions = []
this.$emit('search', item)
}
}
}
</script>
样式优化
添加基础样式增强用户体验。
.search-container {
display: flex;
gap: 10px;
}
input {
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
}
button {
padding: 8px 16px;
background-color: #42b983;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.search-suggestions ul {
list-style: none;
padding: 0;
border: 1px solid #eee;
}
.search-suggestions li {
padding: 8px;
cursor: pointer;
}
.search-suggestions li:hover {
background-color: #f5f5f5;
}
与父组件通信
父组件通过监听事件获取搜索值。
<template>
<div>
<SearchComponent @search="onSearch" />
<div v-if="results">{{ results }}</div>
</div>
</template>
<script>
import SearchComponent from './SearchComponent.vue'
export default {
components: { SearchComponent },
data() {
return {
results: ''
}
},
methods: {
onSearch(query) {
this.results = `正在搜索: ${query}`
// 实际调用API逻辑
}
}
}
</script>






