vue实现双列商品卡片
Vue 实现双列商品卡片
使用 Vue 实现双列商品卡片可以通过 flex 布局或 grid 布局实现,以下是两种常见方法:
方法一:使用 Flex 布局
<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>
export default {
data() {
return {
products: [
{ id: 1, name: '商品1', price: '¥100', image: 'image1.jpg' },
{ id: 2, name: '商品2', price: '¥200', image: 'image2.jpg' },
// 更多商品数据...
]
}
}
}
</script>
<style>
.product-list {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
gap: 10px; /* 可选,卡片间距 */
}
.product-card {
width: calc(50% - 5px); /* 减去间距的一半 */
border: 1px solid #eee;
padding: 10px;
box-sizing: border-box;
}
</style>
方法二:使用 Grid 布局
<template>
<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>
</template>
<script>
export default {
data() {
return {
products: [
{ id: 1, name: '商品1', price: '¥100', image: 'image1.jpg' },
{ id: 2, name: '商品2', price: '¥200', image: 'image2.jpg' },
// 更多商品数据...
]
}
}
}
</script>
<style>
.product-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 10px; /* 卡片间距 */
}
.product-card {
border: 1px solid #eee;
padding: 10px;
}
</style>
响应式调整
如果需要在小屏幕设备上显示单列,可以添加媒体查询:
@media (max-width: 600px) {
.product-list {
flex-direction: column;
}
.product-card {
width: 100%;
}
/* 或针对 Grid 布局 */
.product-grid {
grid-template-columns: 1fr;
}
}
动态加载数据
如果商品数据是通过 API 获取的,可以使用 axios 或 fetch:
export default {
data() {
return {
products: []
}
},
async created() {
try {
const response = await axios.get('/api/products');
this.products = response.data;
} catch (error) {
console.error('获取商品数据失败:', error);
}
}
}
以上方法均可实现双列商品卡片布局,根据项目需求选择合适的方式。







