vue实现商品列表
Vue实现商品列表
数据准备
商品列表通常需要一个数组来存储商品信息,每个商品对象包含id、名称、价格、图片等属性。可以在组件的data中定义初始数据或通过API获取。
data() {
return {
products: [
{ id: 1, name: '商品1', price: 100, image: 'product1.jpg' },
{ id: 2, name: '商品2', price: 200, image: 'product2.jpg' }
]
}
}
模板渲染
使用v-for指令循环渲染商品列表,结合插值表达式显示商品信息。建议为每个商品项添加key属性以提高渲染性能。

<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>
样式设计
为商品列表添加CSS样式,可以使用Flexbox或Grid布局实现响应式设计。建议为商品项设置固定宽高和间距。
.product-list {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
gap: 20px;
}
.product-item {
border: 1px solid #ddd;
padding: 15px;
border-radius: 5px;
}
.product-item img {
width: 100%;
height: 200px;
object-fit: cover;
}
分页功能
对于大量商品数据,可以实现分页功能。使用计算属性处理分页逻辑,添加页码切换按钮。

computed: {
paginatedProducts() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
return this.products.slice(start, end);
}
}
筛选和排序
添加筛选和排序功能提升用户体验。可以使用计算属性根据用户选择的条件处理商品数据。
computed: {
filteredProducts() {
return this.products.filter(product => {
return product.name.includes(this.searchKeyword) &&
product.price >= this.minPrice
}).sort((a, b) => {
if (this.sortBy === 'price') return a.price - b.price
return 0
})
}
}
交互功能
为商品项添加点击事件,跳转到商品详情页或加入购物车功能。使用Vue的事件绑定机制实现交互。
<button @click="addToCart(product)">加入购物车</button>
methods: {
addToCart(product) {
this.$emit('add-to-cart', product)
}
}





