v-for 循環(huán)數(shù)組,使用flex方法使每個元素寬度相等

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。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容