Vue实现淘宝搜索功能
Vue实现淘宝搜索功能的关键步骤
搭建Vue项目结构 使用Vue CLI创建项目,安装必要依赖如vue-router、axios。创建搜索组件Search.vue,商品列表组件GoodsList.vue,以及详情页组件Detail.vue。
实现搜索框组件 在Search.vue中使用v-model绑定输入框,监听input事件实现实时搜索建议。添加防抖函数优化性能,避免频繁请求。
<template>
<div class="search-box">
<input
v-model="keyword"
@input="handleInput"
placeholder="搜索商品..."
/>
<ul v-if="suggestions.length" class="suggestions">
<li v-for="(item,index) in suggestions" :key="index">
{{ item }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
keyword: '',
suggestions: [],
timer: null
}
},
methods: {
handleInput() {
clearTimeout(this.timer)
this.timer = setTimeout(() => {
this.fetchSuggestions()
}, 300)
},
async fetchSuggestions() {
if(this.keyword.trim()) {
const res = await axios.get('/api/suggest', {params: {q: this.keyword}})
this.suggestions = res.data
}
}
}
}
</script>
后端API接口设计 创建Express或Spring Boot后端服务,提供三个核心接口:
/api/suggest返回搜索建议/api/search返回商品列表/api/detail返回商品详情
商品列表展示 在GoodsList.vue组件中,使用v-for渲染商品卡片,包含图片、标题、价格等信息。实现分页加载和无限滚动。
<template>
<div class="goods-container">
<div
v-for="goods in goodsList"
:key="goods.id"
class="goods-item"
@click="goDetail(goods.id)"
>
<img :src="goods.image" />
<p class="title">{{ goods.title }}</p>
<p class="price">¥{{ goods.price }}</p>
</div>
<div v-if="loading" class="loading">加载中...</div>
</div>
</template>
搜索状态管理 对于复杂场景可使用Vuex管理搜索状态:
// store/modules/search.js
const state = {
history: [],
hotKeywords: [],
currentKeyword: ''
}
const mutations = {
ADD_HISTORY(state, keyword) {
state.history.unshift(keyword)
},
SET_KEYWORD(state, keyword) {
state.currentKeyword = keyword
}
}
搜索结果排序筛选 实现价格排序、销量排序等筛选功能:
computed: {
sortedGoods() {
return [...this.goodsList].sort((a,b) => {
if(this.sortBy === 'price') {
return a.price - b.price
} else {
return b.sales - a.sales
}
})
}
}
性能优化建议
- 使用keep-alive缓存搜索组件
- 图片懒加载使用vue-lazyload
- 接口数据缓存减少请求
- 重要数据预加载提升体验
完整项目结构参考
src/
├── components/
│ ├── Search.vue
│ ├── GoodsList.vue
│ └── GoodsItem.vue
├── views/
│ ├── Home.vue
│ └── Detail.vue
├── router/
│ └── index.js
├── store/
│ └── modules/
│ └── search.js
└── api/
└── search.js
实现过程中需注意移动端适配、错误处理、空状态展示等细节,可根据实际需求扩展历史记录、热门搜索等功能模块。







