vue 实现商品页面
Vue 实现商品页面的核心方法
商品数据管理
使用 Vue 的响应式特性管理商品数据,通过 data 或 Vuex/Pinia 存储商品信息。典型数据结构包含 id, name, price, images, description 等字段。
data() {
return {
product: {
id: 1,
name: '示例商品',
price: 99,
images: ['image1.jpg', 'image2.jpg'],
description: '商品详细描述...'
}
}
}
商品展示组件
创建可复用的商品卡片组件,使用 v-for 渲染商品列表。通过 props 接收商品数据,实现图片轮播、价格显示等功能。
<template>
<div class="product-card">
<img :src="product.images[0]" :alt="product.name">
<h3>{{ product.name }}</h3>
<p>价格: ¥{{ product.price }}</p>
</div>
</template>
路由配置
配置动态路由实现商品详情页,通过 params 传递商品ID。在 created 钩子中根据ID获取商品数据。

const routes = [
{ path: '/product/:id', component: ProductDetail }
]
购物车功能
实现 addToCart 方法,使用事件总线或状态管理工具同步购物车数据。添加商品时需考虑数量增减和去重逻辑。
methods: {
addToCart() {
this.$store.dispatch('cart/addItem', this.product)
}
}
交互优化
加入图片懒加载、骨架屏加载状态、价格动画等交互细节。使用 transition 组件实现平滑的页面过渡效果。

<transition name="fade">
<ProductGallery v-if="loaded" />
</transition>
后端数据对接
通过 axios 或 fetch 与后端API交互,在 mounted 生命周期获取商品数据。处理加载状态和错误情况。
async fetchProduct() {
try {
const res = await axios.get(`/api/products/${this.$route.params.id}`)
this.product = res.data
} catch (error) {
console.error(error)
}
}
移动端适配
使用响应式布局确保多设备兼容,通过媒体查询调整商品列表的列数。触屏设备需优化图片预览和按钮操作区域。
@media (max-width: 768px) {
.product-grid {
grid-template-columns: repeat(2, 1fr);
}
}






