vue实现商品布局
Vue实现商品布局的方法
使用Grid布局
通过CSS Grid可以快速实现商品网格布局。在Vue组件中,结合v-for循环渲染商品列表,利用Grid控制行列间距。
<template>
<div class="product-grid">
<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>
<style>
.product-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
gap: 20px;
}
.product-item {
border: 1px solid #eee;
padding: 10px;
text-align: center;
}
</style>
使用Flexbox布局
Flexbox适合需要灵活对齐的商品列表。通过设置flex-wrap实现自动换行。

<template>
<div class="product-flex">
<div v-for="product in products" :key="product.id" class="flex-item">
<!-- 商品内容 -->
</div>
</div>
</template>
<style>
.product-flex {
display: flex;
flex-wrap: wrap;
gap: 15px;
}
.flex-item {
flex: 1 1 200px;
}
</style>
结合第三方组件库
使用Element UI或Ant Design Vue等库快速搭建布局:

<template>
<a-row :gutter="16">
<a-col v-for="product in products" :key="product.id" :span="6">
<a-card>
<img :src="product.image" style="width:100%">
<template #actions>
<span>¥{{ product.price }}</span>
</template>
</a-card>
</a-col>
</a-row>
</template>
响应式设计
通过媒体查询实现不同屏幕尺寸下的布局变化:
@media (max-width: 768px) {
.product-grid {
grid-template-columns: repeat(2, 1fr);
}
}
@media (max-width: 480px) {
.product-grid {
grid-template-columns: 1fr;
}
}
动态加载商品
结合API异步加载商品数据:
export default {
data() {
return {
products: []
}
},
async created() {
const res = await fetch('/api/products')
this.products = await res.json()
}
}





