vue实现天猫导航
Vue 实现天猫导航
项目结构
使用 Vue CLI 创建项目,安装必要依赖如 vue-router、axios。目录结构建议如下:
src/
├── components/
│ ├── Header.vue # 顶部导航
│ ├── MainNav.vue # 主分类导航
│ ├── SubNav.vue # 二级分类导航
│ └── SearchBar.vue # 搜索框组件
├── views/
│ ├── Home.vue # 首页
│ └── Category.vue # 分类页
├── router/
│ └── index.js # 路由配置
└── App.vue # 根组件
顶部导航实现
顶部导航包含用户登录、店铺入口等信息,使用 Flex 布局实现:
<template>
<div class="top-header">
<div class="left">
<span>天猫首页</span>
<span>喵,请登录</span>
<span>免费注册</span>
</div>
<div class="right">
<span>我的订单</span>
<span>购物车</span>
</div>
</div>
</template>
<style scoped>
.top-header {
display: flex;
justify-content: space-between;
background: #f2f2f2;
padding: 5px 20px;
}
</style>
主分类导航
主分类采用横向滚动式设计,数据通过 v-for 动态渲染:
<template>
<div class="main-nav">
<div v-for="item in navList" :key="item.id" class="nav-item">
<img :src="item.icon" />
<span>{{ item.name }}</span>
</div>
</div>
</template>
<script>
export default {
data() {
return {
navList: [
{ id: 1, name: '女装', icon: 'icon-path' },
{ id: 2, name: '男装', icon: 'icon-path' }
]
}
}
}
</script>
<style scoped>
.main-nav {
display: flex;
overflow-x: auto;
white-space: nowrap;
}
.nav-item {
padding: 0 15px;
text-align: center;
}
</style>
搜索框组件
集成搜索建议功能,使用 v-model 绑定输入值:
<template>
<div class="search-box">
<input
v-model="keyword"
@keyup.enter="search"
placeholder="搜索商品"
/>
<button @click="search">搜索</button>
<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: []
}
},
methods: {
async search() {
if (this.keyword.trim()) {
const res = await axios.get('/api/search?s=' + this.keyword)
this.suggestions = res.data.suggestions
}
}
}
}
</script>
路由配置
配置分类页面的动态路由:
// router/index.js
{
path: '/category/:id',
name: 'Category',
component: () => import('../views/Category.vue')
}
交互优化
-
主分类导航添加鼠标悬停效果:
.nav-item:hover { color: #FF0036; transform: translateY(-2px); } -
搜索框防抖处理:
import _ from 'lodash' export default { watch: { keyword: _.debounce(function(newVal) { this.fetchSuggestions(newVal) }, 300) } }
数据获取
通过 Axios 获取导航数据:
async created() {
try {
const res = await axios.get('/api/nav')
this.navList = res.data
} catch (error) {
console.error(error)
}
}
注意事项
- 移动端需添加 touch 事件支持
- 图标建议使用 SVG 雪碧图或 iconfont
- 二级分类建议使用 CSS 过渡动画
- 路由切换时保持导航状态可用 Vuex 管理







