可以通过计算属性来获取传入slot的数量,然后根据数量进行分行展示。具体实现可以参考以下代码:

<template>
  <div class="container">
    <div v-for="(row, index) in rows" :key="index" class="row">
      <slot v-for="(slot, i) in getSlotsInRow(index)" :name="'slot-' + i" />
    </div>
  </div>
</template>

<script>
export default {
  computed: {
    slotCount() {
      return this.$slots.default ? this.$slots.default.length : 0;
    },
    rows() {
      const rows = [];
      for (let i = 0; i < this.slotCount; i += 6) {
        rows.push(i);
      }
      return rows;
    },
  },
  methods: {
    getSlotsInRow(rowIndex) {
      return this.$slots.default.slice(rowIndex, rowIndex + 6);
    },
  },
};
</script>

<style>
.container {
  display: flex;
  flex-wrap: wrap;
}
.row {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 10px;
}
</style>

在模板中,我们使用v-for遍历计算属性rows,每一行有6个slot,然后在每行中再使用v-for遍历getSlotsInRow方法获取这一行的slot,同时设置slot的name为"slot-" + i,这样就可以动态渲染slot了。

计算属性slotCount用于获取传入slot的数量,然后根据数量计算出应该有多少行,计算属性rows返回一个数组,包含每一行的起始下标。

方法getSlotsInRow用于根据行号获取这一行的slot,slice方法用于截取数组中的一部分。

最后,我们还需要设置一些样式,让每一行显示为一个flex容器,超出容器宽度时自动换行。


原文地址: http://www.cveoy.top/t/topic/w8I 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录