vue实现商品页面
Vue 实现商品页面的核心步骤
项目初始化与依赖安装
使用 Vue CLI 或 Vite 创建项目,安装必要依赖如 vue-router、axios 和 UI 库(例如 element-plus)。通过命令 npm create vue@latest 初始化项目后,安装基础依赖:
npm install axios vue-router element-plus
路由配置
在 router/index.js 中配置商品页面的路由,动态路由可用于商品详情页:
const routes = [
{
path: '/products',
component: () => import('@/views/ProductList.vue')
},
{
path: '/product/:id',
component: () => import('@/views/ProductDetail.vue')
}
]
商品列表组件
创建 ProductList.vue,通过 axios 获取商品数据并渲染。使用 v-for 循环展示商品卡片,包含图片、名称、价格等基础信息:
<template>
<div class="product-list">
<div v-for="product in products" :key="product.id" class="product-card">
<img :src="product.image" :alt="product.name">
<h3>{{ product.name }}</h3>
<p>¥{{ product.price }}</p>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return { products: [] };
},
async created() {
const res = await axios.get('/api/products');
this.products = res.data;
}
};
</script>
商品详情页组件
在 ProductDetail.vue 中,通过路由参数 $route.params.id 获取商品 ID,请求详情数据。展示商品大图、描述、规格及加入购物车按钮:
<template>
<div v-if="product" class="product-detail">
<img :src="product.image" class="main-image">
<h1>{{ product.name }}</h1>
<p class="price">¥{{ product.price }}</p>
<button @click="addToCart">加入购物车</button>
</div>
</template>
<script>
export default {
data() {
return { product: null };
},
async created() {
const res = await axios.get(`/api/products/${this.$route.params.id}`);
this.product = res.data;
},
methods: {
addToCart() {
// 购物车逻辑
}
}
};
</script>
状态管理(可选)
复杂场景可使用 Pinia 管理商品和购物车状态。创建 stores/cart.js 存储购物车数据:
import { defineStore } from 'pinia';
export const useCartStore = defineStore('cart', {
state: () => ({
items: []
}),
actions: {
addItem(product) {
this.items.push(product);
}
}
});
样式与布局
使用 Flex 或 Grid 布局商品列表,确保响应式设计。通过 SCSS 或 CSS 变量统一主题色:
.product-list {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
gap: 20px;
}
.product-card {
border: 1px solid #eee;
padding: 10px;
}
API 数据模拟
开发阶段可用 Mock.js 或 json-server 模拟接口。安装 json-server 后创建 db.json:
npm install -g json-server
json-server --watch db.json
示例 db.json 结构:
{
"products": [
{ "id": 1, "name": "商品1", "price": 100, "image": "/images/1.jpg" }
]
}
部署优化
构建时启用代码分割和压缩,配置生产环境 API 地址。在 vite.config.js 中设置代理避免跨域:

export default defineConfig({
server: {
proxy: {
'/api': 'http://localhost:3000'
}
}
})






