vue实现简单商品列表
Vue 实现简单商品列表
创建 Vue 项目
使用 Vue CLI 或 Vite 快速初始化项目。安装依赖后,在 src 目录下新建组件文件(如 ProductList.vue)。
定义商品数据
在组件的 data 或 setup 中定义商品数组,包含商品名称、价格、图片等字段:
data() {
return {
products: [
{ id: 1, name: "商品A", price: 99, image: "image1.jpg" },
{ id: 2, name: "商品B", price: 199, image: "image2.jpg" }
]
};
}
模板渲染
使用 v-for 循环渲染商品列表,通过插值表达式或属性绑定显示数据:
<template>
<div class="product-list">
<div v-for="product in products" :key="product.id" class="product-item">
<img :src="product.image" :alt="product.name">
<h3>{{ product.name }}</h3>
<p>价格: ¥{{ product.price }}</p>
</div>
</div>
</template>
样式设计
通过 CSS 或 SCSS 美化列表布局,例如网格或弹性盒子:
.product-list {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 20px;
}
.product-item {
border: 1px solid #ddd;
padding: 10px;
text-align: center;
}
交互功能
添加点击事件或购物车功能,例如通过方法处理商品点击:
methods: {
handleClick(product) {
console.log("选中商品:", product.name);
}
}
<button @click="handleClick(product)">加入购物车</button>
数据动态化
若需从后端获取数据,可使用 axios 或 fetch 在 created 或 mounted 钩子中请求接口:
async mounted() {
const response = await axios.get("/api/products");
this.products = response.data;
}
组件化拆分
将商品项拆分为子组件(如 ProductItem.vue),通过 props 传递数据:
<ProductItem
v-for="product in products"
:key="product.id"
:product="product"
@add-to-cart="handleAddCart"
/>
状态管理(可选)
对于复杂场景,可通过 Vuex 或 Pinia 全局管理商品状态,实现跨组件通信。







