vue 实现商品展示
使用 Vue 实现商品展示
数据准备
创建一个商品数据数组,包含商品名称、价格、图片链接等信息。
data() {
return {
products: [
{ id: 1, name: "商品A", price: 100, image: "product_a.jpg" },
{ id: 2, name: "商品B", price: 200, image: "product_b.jpg" },
{ id: 3, name: "商品C", price: 300, image: "product_c.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 样式,使商品展示更美观。
.product-list {
display: flex;
flex-wrap: wrap;
gap: 20px;
}
.product-item {
border: 1px solid #ddd;
padding: 10px;
width: 200px;
text-align: center;
}
.product-item img {
width: 100%;
height: 150px;
object-fit: cover;
}
交互功能
添加点击事件,实现商品详情跳转或加入购物车功能。

<button @click="addToCart(product)">加入购物车</button>
methods: {
addToCart(product) {
console.log("加入购物车:", product.name);
// 可调用购物车逻辑
}
}
分页加载
如果商品数据较多,可结合分页组件优化展示。
<pagination :total="totalProducts" @page-change="loadProducts" />
methods: {
loadProducts(page) {
// 调用 API 加载分页数据
}
}
动态数据获取
结合 axios 从后端 API 获取商品数据。
import axios from "axios";
methods: {
fetchProducts() {
axios.get("/api/products").then(response => {
this.products = response.data;
});
}
},
created() {
this.fetchProducts();
}
通过以上方法,可以快速实现 Vue 商品展示功能,并支持扩展交互和动态数据加载。






