vue教程实现商品详情
Vue 实现商品详情页教程
项目初始化
使用 Vue CLI 创建新项目,安装必要依赖如 vue-router 和 axios。
命令示例:
vue create product-detail
cd product-detail
npm install vue-router axios
路由配置
在 src/router/index.js 中配置动态路由,接收商品 ID 参数。
代码示例:
const routes = [
{
path: '/product/:id',
name: 'ProductDetail',
component: () => import('../views/ProductDetail.vue')
}
]
数据请求封装
创建 src/api/product.js 封装商品数据接口,使用 axios 发起请求。
代码示例:
import axios from 'axios'
export function getProductDetail(id) {
return axios.get(`/api/products/${id}`)
}
商品详情组件开发
在 src/views/ProductDetail.vue 中实现核心逻辑:

- 通过
this.$route.params.id获取商品 ID - 在
created钩子中调用接口获取数据 - 使用 v-if 处理加载状态
模板部分示例:
<template>
<div class="product-detail">
<div v-if="loading">加载中...</div>
<div v-else>
<h2>{{ product.name }}</h2>
<img :src="product.image" :alt="product.name">
<p>价格: {{ product.price }}</p>
<p>库存: {{ product.stock }}</p>
</div>
</div>
</template>
样式优化
添加 CSS 样式增强视觉效果:

- 商品图片设置最大宽度
- 价格标签使用醒目颜色
- 添加过渡动画提升体验
样式示例:
.product-detail {
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
.product-detail img {
max-width: 100%;
height: auto;
}
.price {
color: #f56c6c;
font-weight: bold;
}
错误处理
在数据请求中添加错误捕获逻辑,显示友好提示:
async created() {
try {
const res = await getProductDetail(this.$route.params.id)
this.product = res.data
} catch (error) {
this.error = '商品加载失败,请稍后重试'
} finally {
this.loading = false
}
}
组件复用优化
将商品图片展示、价格标签等拆分为子组件,通过 props 传递数据。
子组件示例:
<template>
<div class="price-display">
<span class="currency">¥</span>
<span class="amount">{{ value }}</span>
</div>
</template>
<script>
export default {
props: {
value: Number
}
}
</script>





