Vue中实现动态横向均匀排列块元素

最终效果

在这里插入图片描述

响应式均匀排列

实现思路

整体思路是将遍历元素的父布局设置为flex,并且将justify-content设置为space-around,但此时最后一行如果和上面均匀分布的数量不一样(少于),那么会出现剧中均匀分布,而不是想上面图片那样居左对齐排列。至于为什么不将justify-content设置为start,是因为如果设置为了start的话,右侧大概率会出现空白,导致两侧不是均匀分布的,影响体验。

我这里的解决方案是通过window得resize事件,监听屏幕的变化,在初始化页面的时候首先根据排列的元素宽度计算出当前宽度的屏幕中每一行会均匀排列多少个,然后再计算出最后一个行的元素有几个,那么这时候我们用每行均匀个数减去最后一行的个数就是我们需要补齐的个数,这里补齐的是空白的占位元素。

实现代码

Photos.vue :

<script setup>
import { Plus, Search, UploadFilled } from '@element-plus/icons-vue';
import { onMounted, reactive, ref } from 'vue';

const imageList = reactive(["https://www.devcat.cn/res/img/avatar.png","https://www.devcat.cn/res/img/smart-index.png","https://www.devcat.cn/res/img/avatar.png"])

const subCount = ref(0)

const initList = () => {
    let count = parseInt((window.innerWidth-10) / 220)
    subCount.value =  count - (18 - count*(parseInt(18 / count)))
}

onMounted(()=>{
    initList()
    window.addEventListener('resize',()=>{
        initList()
    })
})

</script>

<template>
    <main>
        <div class="toolBar">
            <el-input :suffix-icon="Search" placeholder="关键字搜索" style="width: 300px;"></el-input>
            <el-button :icon="Plus" type="default" style="margin-left:10px;">新建相册</el-button>
            <el-button :icon="UploadFilled" type="primary" style="margin-left:10px;">上传图片</el-button>
        </div>
        <div class="photoBox">
            <div class="photoItem" v-for="item in 18" :key="item">
                <el-image :initial-index="item-1" :preview-src-list="imageList" loading="lazy" style="width:200px; height:200px" fit="contain" src="https://www.devcat.cn/res/img/avatar.png"></el-image>
                <div class="info">avatar{{ item }}.png</div>
            </div>
            <div style="width: 200px; height: 200px; margin: 10px;" v-for="item in subCount" :key="item"></div>
        </div>
    </main>
</template>

<style scoped>
main{
    padding: 10px;
}
.toolBar{
    border-bottom: 1px solid #bbb;
    padding-bottom: 10px;
}
.photoBox{
    width: calc(100% - 20px);
    display: flex;
    justify-content: space-around;
    flex-wrap: wrap;
    padding: 10px;

}
.photoItem{
    margin: 10px;
    cursor: pointer;
}
.info{
    text-align: center;
    color: #444;
}
.helpLayout{
    width: auto;
}
</style>

以上只针对这种需求的一种解决方案,如果有用的话===>** 点赞+收藏 **

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@胡海龙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值