vue实现搜索栏
实现基础搜索栏功能
在Vue中创建一个基础搜索栏需要结合v-model实现数据双向绑定,监听用户输入并触发搜索逻辑。以下是一个简单实现:
<template>
<div>
<input
type="text"
v-model="searchQuery"
placeholder="输入搜索内容"
@keyup.enter="performSearch"
/>
<button @click="performSearch">搜索</button>
</div>
</template>
<script>
export default {
data() {
return {
searchQuery: ''
}
},
methods: {
performSearch() {
if(this.searchQuery.trim()) {
// 实际搜索逻辑
console.log('搜索:', this.searchQuery);
// 可以在这里触发API调用或过滤本地数据
}
}
}
}
</script>
添加防抖优化
为防止频繁触发搜索请求,通常需要添加防抖功能:
import { debounce } from 'lodash';
export default {
data() {
return {
searchQuery: '',
debouncedSearch: null
}
},
created() {
this.debouncedSearch = debounce(this.performSearch, 500);
},
methods: {
handleInput() {
this.debouncedSearch();
},
performSearch() {
// 实际搜索逻辑
}
}
}
模板中需要将@input="handleInput"绑定到输入框。
结合API请求实现远程搜索
当需要从服务器获取搜索结果时,可以结合axios等HTTP库:
methods: {
async performSearch() {
try {
const response = await axios.get('/api/search', {
params: { q: this.searchQuery }
});
this.searchResults = response.data;
} catch (error) {
console.error('搜索出错:', error);
}
}
}
本地数据过滤实现
对于本地数据的搜索过滤,可以使用计算属性:
computed: {
filteredItems() {
return this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
);
}
}
添加搜索建议功能
实现搜索建议需要额外的组件和逻辑:
<template>
<div class="search-container">
<input
v-model="searchQuery"
@input="showSuggestions = true"
@blur="hideSuggestions"
/>
<ul v-show="showSuggestions && suggestions.length">
<li
v-for="(suggestion, index) in suggestions"
:key="index"
@mousedown="selectSuggestion(suggestion)"
>
{{ suggestion }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
searchQuery: '',
showSuggestions: false,
allSuggestions: ['建议1', '建议2', '建议3']
}
},
computed: {
suggestions() {
return this.allSuggestions.filter(s =>
s.toLowerCase().includes(this.searchQuery.toLowerCase())
);
}
},
methods: {
selectSuggestion(suggestion) {
this.searchQuery = suggestion;
this.showSuggestions = false;
this.performSearch();
},
hideSuggestions() {
setTimeout(() => {
this.showSuggestions = false;
}, 200);
}
}
}
</script>
样式优化
为搜索栏添加基础样式:
.search-container {
position: relative;
width: 300px;
}
input {
width: 100%;
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
}
ul {
position: absolute;
width: 100%;
margin: 0;
padding: 0;
list-style: none;
background: white;
border: 1px solid #ddd;
border-top: none;
z-index: 10;
}
li {
padding: 8px;
cursor: pointer;
}
li:hover {
background-color: #f5f5f5;
}
这些实现方式可以根据实际需求进行组合和扩展,构建出功能完善的搜索栏组件。







