vue实现淘宝搜索
Vue 实现淘宝搜索功能
淘宝搜索功能涉及关键词输入、实时搜索建议、搜索结果展示等核心模块。以下是基于 Vue 的实现方案:
搜索框与关键词输入
使用 Vue 的 v-model 实现双向绑定,监听用户输入:
<template>
<div class="search-container">
<input
v-model="searchQuery"
@input="handleInput"
placeholder="搜索商品..."
/>
<button @click="performSearch">搜索</button>
</div>
</template>
export default {
data() {
return {
searchQuery: '',
suggestions: []
}
},
methods: {
handleInput() {
if (this.searchQuery.trim()) {
this.fetchSuggestions();
}
}
}
}
实时搜索建议
通过防抖函数优化高频请求:
import { debounce } from 'lodash';
export default {
created() {
this.debouncedFetch = debounce(this.fetchSuggestions, 300);
},
methods: {
handleInput() {
this.debouncedFetch();
},
async fetchSuggestions() {
try {
const res = await axios.get('/api/suggestions', {
params: { q: this.searchQuery }
});
this.suggestions = res.data;
} catch (error) {
console.error(error);
}
}
}
}
搜索结果展示
使用条件渲染展示结果列表:
<ul v-if="suggestions.length" class="suggestion-list">
<li
v-for="(item, index) in suggestions"
:key="index"
@click="selectSuggestion(item)"
>
{{ item }}
</li>
</ul>
完整搜索逻辑
整合搜索执行与结果分页:
export default {
data() {
return {
searchResults: [],
currentPage: 1,
totalPages: 0
}
},
methods: {
async performSearch() {
const params = {
q: this.searchQuery,
page: this.currentPage
};
const res = await axios.get('/api/search', { params });
this.searchResults = res.data.items;
this.totalPages = res.data.totalPages;
},
selectSuggestion(item) {
this.searchQuery = item;
this.performSearch();
}
}
}
样式优化
添加基础样式提升用户体验:
.search-container {
position: relative;
width: 500px;
margin: 0 auto;
}
.suggestion-list {
position: absolute;
width: 100%;
background: white;
border: 1px solid #eee;
max-height: 300px;
overflow-y: auto;
}
.suggestion-list li {
padding: 8px 12px;
cursor: pointer;
}
.suggestion-list li:hover {
background-color: #f5f5f5;
}
性能优化方案
- 使用虚拟滚动技术处理大量搜索结果
- 实现客户端缓存减少重复请求
- 添加加载状态提升交互体验
- 对长列表进行分页或无限滚动处理
高级功能扩展
- 搜索历史记录本地存储
- 热门搜索推荐模块
- 多条件筛选面板
- 搜索结果排序功能
- 图片懒加载优化
该实现方案可根据实际项目需求进行调整,核心在于处理好用户输入与数据响应的实时交互,同时兼顾性能与用户体验。







