vue实现外卖页面
实现外卖页面的核心步骤
页面结构与组件划分 外卖页面通常分为顶部导航栏、商品分类侧边栏、商品列表和购物车组件。使用Vue的单文件组件(SFC)模式进行模块化开发。
数据管理与状态共享 采用Vuex或Pinia管理全局状态,包括商品数据、购物车状态和用户选择。商品数据通过API异步获取并存储在store中。
// store示例(Pinia)
export const useFoodStore = defineStore('food', {
state: () => ({
foods: [],
cart: []
}),
actions: {
async fetchFoods() {
this.foods = await api.get('/foods')
}
}
})
关键功能实现方案
商品分类联动 侧边栏分类与商品列表实现滚动联动效果。使用Intersection Observer API监测元素位置,或通过计算scrollTop值实现。
// 分类高亮逻辑
const activeCategory = ref(0)
const onScroll = () => {
const scrollTop = container.value.scrollTop
categoryOffsets.value.forEach((offset, index) => {
if (scrollTop >= offset) activeCategory.value = index
})
}
购物车功能 购物车组件需要实现添加/删除商品、数量增减和金额计算。使用Vue的响应式系统自动更新视图。
<!-- 购物车模板示例 -->
<div v-for="item in cart" :key="item.id">
<span>{{ item.name }}</span>
<button @click="decrement(item)">-</button>
<span>{{ item.quantity }}</span>
<button @click="increment(item)">+</button>
</div>
性能优化技巧
虚拟滚动技术 商品列表采用虚拟滚动解决大量DOM渲染问题。使用vue-virtual-scroller等库实现。
// 安装虚拟滚动库
import { RecycleScroller } from 'vue-virtual-scroller'
components: { RecycleScroller }
图片懒加载 商品图片使用Intersection Observer实现懒加载,减少初始请求压力。
<img v-lazy="food.image" alt="food">
完整项目结构参考
src/
├── components/
│ ├── NavBar.vue
│ ├── CategorySidebar.vue
│ ├── FoodList.vue
│ └── ShoppingCart.vue
├── stores/
│ └── food.js
├── views/
│ └── Takeaway.vue
└── utils/
└── scroll.js





