vue实现商品详情功能
Vue 实现商品详情功能
数据获取与展示
通过 API 接口获取商品详情数据,使用 axios 或 fetch 发起请求。将返回的数据存储在组件的 data 中,并在模板中动态渲染。
data() {
return {
product: {
id: null,
name: '',
price: 0,
description: '',
images: []
}
}
},
methods: {
fetchProductDetail(id) {
axios.get(`/api/products/${id}`)
.then(response => {
this.product = response.data;
});
}
},
created() {
this.fetchProductDetail(this.$route.params.id);
}
图片轮播展示
使用第三方库如 vue-awesome-swiper 实现商品图片的轮播效果。配置轮播参数,如自动播放、导航按钮等。
<template>
<swiper :options="swiperOption">
<swiper-slide v-for="(image, index) in product.images" :key="index">
<img :src="image" alt="商品图片">
</swiper-slide>
<div class="swiper-pagination" slot="pagination"></div>
</swiper>
</template>
<script>
import { Swiper, SwiperSlide } from 'vue-awesome-swiper';
import 'swiper/css/swiper.css';
export default {
components: {
Swiper,
SwiperSlide
},
data() {
return {
swiperOption: {
pagination: {
el: '.swiper-pagination'
},
loop: true,
autoplay: {
delay: 3000
}
}
}
}
}
</script>
商品规格选择
实现商品规格选择功能,如颜色、尺寸等。通过 v-model 绑定用户选择的规格,实时更新显示。
<template>
<div v-for="(spec, index) in product.specs" :key="index">
<h3>{{ spec.name }}</h3>
<div class="spec-options">
<button
v-for="(option, i) in spec.options"
:key="i"
@click="selectSpec(index, i)"
:class="{ active: spec.selected === i }"
>
{{ option }}
</button>
</div>
</div>
</template>
<script>
data() {
return {
product: {
specs: [
{
name: '颜色',
options: ['红色', '蓝色', '黑色'],
selected: null
},
{
name: '尺寸',
options: ['S', 'M', 'L'],
selected: null
}
]
}
}
},
methods: {
selectSpec(specIndex, optionIndex) {
this.product.specs[specIndex].selected = optionIndex;
}
}
</script>
购物车功能
实现加入购物车功能,通过调用购物车 API 接口,传递商品 ID 和选择的规格信息。
methods: {
addToCart() {
const selectedSpecs = this.product.specs.map(spec => {
return spec.options[spec.selected];
});
axios.post('/api/cart', {
productId: this.product.id,
specs: selectedSpecs,
quantity: 1
}).then(response => {
alert('已加入购物车');
});
}
}
商品评价展示
展示商品的用户评价,支持分页加载。通过调用评价 API 接口获取数据,并在页面中渲染。
<template>
<div class="reviews">
<div v-for="review in reviews" :key="review.id" class="review-item">
<h3>{{ review.user }}</h3>
<p>{{ review.content }}</p>
<span>{{ review.date }}</span>
</div>
<button @click="loadMoreReviews" v-if="hasMore">加载更多</button>
</div>
</template>
<script>
data() {
return {
reviews: [],
page: 1,
hasMore: true
}
},
methods: {
fetchReviews() {
axios.get(`/api/products/${this.product.id}/reviews?page=${this.page}`)
.then(response => {
this.reviews = [...this.reviews, ...response.data.reviews];
this.hasMore = response.data.hasMore;
});
},
loadMoreReviews() {
this.page++;
this.fetchReviews();
}
},
created() {
this.fetchReviews();
}
</script>
响应式布局
使用 CSS 媒体查询或 Vue 的响应式工具确保商品详情页在不同设备上都能良好显示。







