1.容器設(shè)置
<div class="container">
<div
v-for="(item, index) in paddedList"
:key="index"
class="item"
:style="{ visibility: index < list.length ? 'visible' : 'hidden' }"
>
{{ item }}
</div>
</div>
css
.container {
display: flex;
flex-wrap: wrap; /* 允許換行 */
gap: 10px; /* 元素間距 */
}
2.子元素固定比例寬度
通過calc計算每項寬度,確保每行4個元素等寬:
.item {
flex: 0 0 calc((100% - 30px) / 4); /* 總間隙為3個10px(4項間隔為3個) */
background: #f0f0f0;
height: 100px;
}
3.處理最后一行對齊
當元素數(shù)量不足4的倍數(shù)時,補充空元素占位并隱藏:
export default {
data() {
return {
list: [...Array(13).keys()] // 示例數(shù)據(jù)(13個元素)
}
},
computed: {
paddedList() {
const remainder = this.list.length % 4;
return remainder === 0
? this.list
: [...this.list, ...Array(4 - remainder).fill(null)];
}
}
};
關(guān)鍵優(yōu)化點
動態(tài)補齊數(shù)據(jù)
通過paddedList計算屬性補充空元素,使總數(shù)量達到4的倍數(shù)(如13→16),避免最后一行元素寬度拉伸異常15。
隱藏占位元素
通過:style="{ visibility: index < list.length ? 'visible' : 'hidden' }"隱藏占位元素,避免空白區(qū)域影響交互23。
間隙精確計算
calc((100% - 30px)/4)中30px對應3個間隔(每行4個元素有3個間隙)14。