VueJS-如何使用for循环将块中的每一秒元素包装起来



我有四个使用foor循环显示的普通图像,我需要将每一秒的图像都封装在div中。

也就是说,我想得到以下结果

<div>
<div>
<img src="" alt="img">
<img src="" alt="img">
</div>
<div>
<img src="" alt="img">
<img src="" alt="img">
</div>
</div>

这是我在codesandbox 中的代码

<template>
<div class="wrapper">
<div
v-for="(item, index) in homePageImageList"
:key="index"
class="hero-image"
:style="{ backgroundImage: 'url(' + item.imageURL + ')' }"
></div>
</div>
</template>
<script>
export default {
name: "HelloWorld",
data() {
return {
homePageImageList: [
{
imageURL:
"https://timeweb.com/ru/community/article/1d/1d959c23e81024374895da086675b298.jpg",
},
{
imageURL:
"https://timeweb.com/ru/community/article/1d/1d959c23e81024374895da086675b298.jpg",
},
{
imageURL:
"https://timeweb.com/ru/community/article/1d/1d959c23e81024374895da086675b298.jpg",
},
{
imageURL:
"https://timeweb.com/ru/community/article/1d/1d959c23e81024374895da086675b298.jpg",
},
],
};
},
};
</script>
<style scoped>
.wrapper {
display: flex;
justify-content: center;
}
.hero-image {
width: 90px;
height: 90px;
max-width: 100%;
border: 1px solid white;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
position: relative;
}
</style>

我认为这里没有必要进行详细描述,一切都很清楚,我有四个对象存储了一个图片的链接,然后我使用v-for 显示它们

您可以使用slice()方法将数组划分为块。

<template>
<div class="wrapper">
<div
v-for="chunk in Math.ceil(homePageImageList.length / 2)"
:key="'chunk-'+chunk"
class="hero-image"
>
<img :src="item.imageURL" alt="img" :key="'img-'+index" v-for="(item, index) in homePageImageList.slice((chunk - 1) * 2, chunk * 2)">
</div>
</div>
</template>

最新更新