vue实现外卖页面
实现外卖页面的核心步骤
使用Vue实现外卖页面需要结合组件化开发、状态管理、路由和API交互。以下是关键实现方法:
页面结构与组件划分
外卖页面通常分为顶部导航栏、商家信息区、商品分类区、购物车和底部结算栏。Vue组件可划分为:
Header:顶部导航和搜索ShopInfo:商家Logo、名称、评分等信息GoodsCategory:商品分类侧边栏GoodsList:商品列表展示Cart:购物车浮层Checkout:底部结算栏
组件通信使用Vuex管理全局状态,如购物车数据、当前选中分类等。
商品数据获取与渲染
通过axios获取后端API数据,典型数据结构示例:
// 商品分类数据结构
categories: [
{
id: 1,
name: "套餐",
foods: [
{
id: 101,
name: "汉堡套餐",
price: 25,
sales: 100,
description: "含汉堡+薯条+可乐"
}
]
}
]
使用v-for渲染分类和商品列表:
<div v-for="category in categories" :key="category.id">
<h3>{{ category.name }}</h3>
<div v-for="food in category.foods" :key="food.id">
{{ food.name }} - ¥{{ food.price }}
</div>
</div>
购物车功能实现
Vuex store示例:

state: {
cartItems: []
},
mutations: {
addToCart(state, food) {
const existing = state.cartItems.find(item => item.id === food.id)
existing ? existing.quantity++ : state.cartItems.push({...food, quantity: 1})
}
}
组件内调用:
methods: {
addFood(food) {
this.$store.commit('addToCart', food)
}
}
交互优化技巧
实现分类联动滚动:
// 监听滚动位置匹配当前分类
window.addEventListener('scroll', () => {
const scrollTop = document.documentElement.scrollTop
this.categories.forEach((cat, index) => {
const el = document.getElementById(`cat-${cat.id}`)
if (el.offsetTop <= scrollTop + 100) {
this.currentCategory = index
}
})
})
移动端适配要点
-
使用viewport meta标签:
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> -
添加点击延迟解决:

npm install fastclickimport FastClick from 'fastclick' FastClick.attach(document.body) -
使用flex布局适配不同屏幕:
.goods-item { display: flex; padding: 12px; }
性能优化建议
-
商品图片懒加载:
<img v-lazy="food.image"> -
长列表使用虚拟滚动:
npm install vue-virtual-scroller -
路由懒加载:
const Goods = () => import('./components/Goods.vue')
完整项目结构参考
src/
├── api/
│ └── shop.js # 接口请求
├── components/
│ ├── Header.vue
│ ├── ShopInfo.vue
│ └── Cart.vue
├── store/
│ ├── index.js # Vuex主文件
│ └── modules/ # 模块化store
├── views/
│ └── Shop.vue # 主页面
└── main.js






