Vue实现商品详情
Vue实现商品详情页的方法
数据获取与渲染
使用Vue的data属性存储商品详情数据,通过v-for指令循环渲染商品属性列表。结合v-if或v-show控制图片预览、库存状态等动态显示。
data() {
return {
product: {
id: 1,
name: '示例商品',
price: 99.9,
images: ['img1.jpg', 'img2.jpg'],
description: '商品详细描述...',
specs: [{name:'颜色',value:'黑色'}, {name:'尺寸',value:'XL'}]
}
}
}
图片轮播组件
集成第三方库如vue-awesome-swiper实现商品主图轮播效果。配置缩略图导航、自动播放等参数。
import { swiper, swiperSlide } from 'vue-awesome-swiper'
components: { swiper, swiperSlide }
规格选择交互
使用计算属性动态更新可选的规格组合,当用户选择规格时实时更新价格和库存显示。
computed: {
selectedSpec() {
return this.specs.filter(item => item.selected)
}
}
购物车功能
通过Vuex管理全局状态,实现加入购物车功能。触发actions将当前商品数据提交到store。
methods: {
addToCart() {
this.$store.dispatch('addCartItem', {
id: this.product.id,
quantity: this.quantity
})
}
}
服务端数据交互
使用axios封装API请求,在created或mounted生命周期钩子中获取商品详情数据。
async mounted() {
const res = await axios.get(`/api/products/${this.$route.params.id}`)
this.product = res.data
}
移动端适配
通过媒体查询或flex布局确保页面在移动设备正常显示。关键区域如购买按钮采用固定定位。
.buy-bar {
position: fixed;
bottom: 0;
width: 100%;
}
SEO优化
在路由配置中添加商品页面的meta信息,使用vue-meta插件管理页面标题和描述。
metaInfo() {
return {
title: this.product.name,
meta: [{name: 'description', content: this.product.description}]
}
}






