效果图:
代码如下:
<template>
<div class="wrap">
<div class="column">
<img :src="item" alt="" v-for="(item, index) in leftColumn" :key="index">
</div>
<div class="column">
<img :src="item" alt="" v-for="(item, index) in rightColumn" :key="index">
</div>
</div>
</template>
<script>
// 图片列表
const list = [
'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2306490913,2115460294&fm=26&gp=0.jpg',
'https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2850261322,1135324421&fm=26&gp=0.jpg',
'https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3185577376,2639757095&fm=26&gp=0.jpg',
'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2045072227,4071612352&fm=26&gp=0.jpg',
'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=4250510097,1033008477&fm=26&gp=0.jpg',
'https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=4009862980,2222696633&fm=15&gp=0.jpg',
'https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3612860753,3233719888&fm=26&gp=0.jpg',
'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2822955656,271745579&fm=26&gp=0.jpg',
'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2731422450,3042484163&fm=26&gp=0.jpg',
]
export default {
data() {
return {
leftColumn: [],
rightColumn: [],
}
},
mounted() {
this.getColumn();
},
methods: {
// 加载图片
imgLoad() {
const imgArr = list.map(item => {
return new Promise(resolve => {
const img = new Image()
img.src = item;
if (img.complete) {
resolve({ url: item, height: img.height })
} else {
img.onload = img.onerror = () => {
resolve({ url: item, height: img.height })
}
}
})
})
return imgArr;
},
// 遍历加载成功的图片 渲染左右两列
getColumn() {
const arr = this.imgLoad()
let leftHeight = 0
let rightHeight = 0
Promise.all(arr).then(res => {
res.forEach(({ height }, index) => {
if (index === 0) {
this.leftColumn.push(list[index])
leftHeight += height
} else if (index === 1) {
this.rightColumn.push(list[index])
rightHeight += height
} else {
if (leftHeight <= rightHeight) {
this.leftColumn.push(list[index])
leftHeight += height
} else {
this.rightColumn.push(list[index])
rightHeight += height
}
}
})
})
}
}
}
</script>
<style>
.wrap {
width: 100%;
display: flex;
}
.column {
width: 50%;
}
img {
width: 100%;
}
</style>