【问题标题】:Vue JS - How to wrap every second element in a block using a for loopVue JS - 如何使用 for 循环将每个第二个元素包装在一个块中
【发布时间】:2021-07-23 18:31:04
【问题描述】:

我有四个使用 foo 循环显示的普通图像,我需要将第二个图像包裹在一个 div 中。

也就是我想得到如下结果

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

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

这里是my code in 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 显示它们

【问题讨论】:

  • 如果数据是静态的,你可以自己把它们分成子数组。

标签: javascript vue.js for-loop vuejs2


【解决方案1】:

您可以使用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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-13
    • 2018-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-22
    相关资源
    最近更新 更多