Vue项目中如何实现产品列表每行展示三列数据
每行三列产品列表布局实现方案
现存问题
- 产品项直接循环渲染块级div,无网格布局容器,默认垂直逐行排列
- 脚本中
numCols: 3写在data()返回值外部,属于无效语法,不会被组件识别 - 原有h1样式存在重复margin定义、属性值缺失单位的问题,样式不生效
实现方式
采用原生CSS Grid实现,无需引入第三方库,改造成本最低,自动适配容器宽度,30条数据会自动按每行3个排布,满3个自动换行。
修改后完整代码
<template> <div> <p v-if="$fetchState.pending">Fetching products...</p> <p v-else-if="$fetchState.error">An error occurred :(</p> <div v-else> <h1>Lab Türkiye products</h1> <!-- 网格容器 --> <div class="product-grid"> <div v-for="product in products" :key="product.id" class="product-card"> <img title="Card Title" :src="product.images[0]" alt="Product Image" class="mb-2 product-img" /> <h3>{{ product.description }}</h3> <h4>{{ product.price }} TL</h4> </div> </div> </div> </div> </template> <script> export default { data() { // 删除无效的numCols错误写法 return { products: [], }; }, async fetch() { const response = await this.$axios.$get("https://dummyjson.com/products"); this.products = response.products; }, }; </script> <style> h1 { text-align: center; color: yellowgreen; /* 修正原有无效margin写法 */ margin: 2rem auto; } /* 网格容器核心样式 */ .product-grid { display: grid; /* 固定3列等宽 */ grid-template-columns: repeat(3, 1fr); /* 统一控制卡片横纵间距 */ gap: 24px; padding: 0 32px; max-width: 1400px; margin: 0 auto; } /* 单产品卡片基础样式 */ .product-card { padding: 16px; border-radius: 8px; box-shadow: 0 2px 12px rgba(0,0,0,0.1); } .product-img { width: 100%; height: 240px; object-fit: cover; max-width: unset; } h3 { font-size: 1rem; line-height: 1.4; margin: 12px 0; /* 长描述自动截断 */ display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; } h4 { color: #e74c3c; margin: 0; font-size: 1.2rem; } </style>
配置说明
grid-template-columns: repeat(3, 1fr)是三列布局的核心配置,自动把容器宽度等分为3份分配给每个产品卡片gap属性同时控制卡片之间的横向、纵向间距,不需要额外给单个卡片加外边距- 补充的图片适配、长文本截断、卡片阴影为优化样式,不需要可以自行删除
- 如果需要适配移动端,只需要添加媒体查询,在屏幕宽度小于768px时设置
grid-template-columns: 1fr即可切换为单列布局
如果偏好Bootstrap实现,不需要写自定义CSS:给外层容器加
class="container",网格容器加class="row",每个循环的产品项加class="col-4"即可实现完全一致的三列效果。
内容的提问来源于stack exchange,提问作者Hazal Kaya
相关产品推荐
相关产品推荐

