vue实现商品布局
使用 Vue 实现商品布局
数据准备
商品数据通常存储在数组中,每个商品对象包含名称、价格、图片等属性。示例数据结构如下:
data() {
return {
products: [
{ id: 1, name: '商品A', price: 100, image: 'image1.jpg' },
{ id: 2, name: '商品B', price: 200, image: 'image2.jpg' },
// 更多商品...
]
}
}
网格布局实现
使用 CSS Grid 或 Flexbox 实现商品网格排列。以下是 Flexbox 示例:
<div class="product-grid">
<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>
.product-grid {
display: flex;
flex-wrap: wrap;
gap: 20px;
}
.product-card {
width: calc(33.333% - 20px);
border: 1px solid #ddd;
padding: 15px;
box-sizing: border-box;
}
响应式设计
通过媒体查询实现不同屏幕尺寸下的布局调整:
@media (max-width: 768px) {
.product-card {
width: calc(50% - 20px);
}
}
@media (max-width: 480px) {
.product-card {
width: 100%;
}
}
商品卡片组件化
将商品卡片封装为可复用组件:
<!-- ProductCard.vue -->
<template>
<div class="product-card">
<img :src="product.image" :alt="product.name">
<h3>{{ product.name }}</h3>
<p>价格: {{ product.price }}元</p>
<button @click="$emit('add-to-cart', product)">加入购物车</button>
</div>
</template>
<script>
export default {
props: ['product']
}
</script>
分页功能
结合分页组件实现商品分页展示:
<product-card
v-for="product in paginatedProducts"
:key="product.id"
:product="product"
@add-to-cart="handleAddToCart"
/>
<pagination
:total-items="products.length"
:items-per-page="perPage"
@page-changed="handlePageChange"
/>
筛选和排序
添加筛选和排序功能增强用户体验:
computed: {
filteredProducts() {
return this.products.filter(product =>
product.name.includes(this.searchQuery)
)
},
sortedProducts() {
return [...this.filteredProducts].sort((a, b) => {
return this.sortBy === 'price' ? a.price - b.price : 0
})
}
}
动画效果
使用 Vue 过渡效果增强交互体验:
<transition-group name="fade" tag="div" class="product-grid">
<product-card
v-for="product in products"
:key="product.id"
:product="product"
/>
</transition-group>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}



