vue实现商品页面
实现商品页面的基本结构
使用 Vue 的单文件组件(SFC)构建商品页面的基本框架。通常包括商品图片展示区、商品信息区、价格展示、购买按钮等核心模块。
<template>
<div class="product-page">
<div class="product-gallery">
<!-- 商品图片轮播或展示区 -->
</div>
<div class="product-info">
<h1>{{ product.title }}</h1>
<div class="price">{{ formattedPrice }}</div>
<div class="description">{{ product.description }}</div>
<div class="variant-selector" v-if="product.variants">
<!-- 商品规格选择组件 -->
</div>
<button @click="addToCart">加入购物车</button>
</div>
</div>
</template>
商品数据管理
通过 Vue 的 data 或 props 接收商品数据,使用计算属性处理价格格式化等衍生数据。
<script>
export default {
props: {
productData: Object
},
data() {
return {
product: this.productData || {
id: '',
title: '',
price: 0,
images: [],
variants: []
},
selectedVariant: null
}
},
computed: {
formattedPrice() {
return `¥${this.product.price.toFixed(2)}`
}
}
}
</script>
图片展示组件
实现商品图片的展示功能,支持主图切换和缩略图导航。
<template>
<div class="image-gallery">
<div class="main-image">
<img :src="currentImage" :alt="product.title">
</div>
<div class="thumbnails">
<img
v-for="(img, index) in product.images"
:key="index"
:src="img"
@click="currentImage = img"
:class="{ active: currentImage === img }">
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentImage: this.product.images[0]
}
}
}
</script>
商品规格选择
处理商品多规格(如颜色、尺寸)的选择逻辑。
methods: {
selectVariant(variant) {
this.selectedVariant = variant
this.product.price = variant.price
this.currentImage = variant.image || this.product.images[0]
}
}
购物车功能集成
实现加入购物车功能,通常需要与 Vuex 或全局状态管理配合。
methods: {
addToCart() {
const cartItem = {
id: this.product.id,
title: this.product.title,
price: this.product.price,
image: this.currentImage,
variant: this.selectedVariant,
quantity: 1
}
this.$store.dispatch('addToCart', cartItem)
}
}
响应式样式设计
使用 CSS 或 CSS 预处理器确保页面在不同设备上的显示效果。
<style scoped>
.product-page {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 2rem;
}
@media (max-width: 768px) {
.product-page {
grid-template-columns: 1fr;
}
}
.image-gallery {
display: flex;
flex-direction: column;
}
.thumbnails {
display: flex;
gap: 0.5rem;
margin-top: 1rem;
}
.thumbnails img {
width: 60px;
height: 60px;
object-fit: cover;
cursor: pointer;
border: 2px solid transparent;
}
.thumbnails img.active {
border-color: #42b983;
}
</style>
商品详情动态加载
通过路由参数获取商品ID,从API加载商品数据。

async created() {
const productId = this.$route.params.id
try {
const response = await axios.get(`/api/products/${productId}`)
this.product = response.data
} catch (error) {
console.error('加载商品失败:', error)
}
}






