在 Vue 组件中,可以根据传入插槽的数量来动态调整布局,例如将 6 个插槽排成一行,超过 6 个就换行。由于插槽是动态的,无法通过名称来标识,可以使用 $slots.default 来获取所有未命名的插槽,并根据插槽数量进行布局。

例如,可以使用计算属性来获取插槽数量,并根据数量动态绑定样式:

<template>
  <div class='container'>
    <div v-for='(slot, index) in slots' :key='index' class='row'>
      <slot v-for='(item, i) in slot' :key='i' />
    </div>
  </div>
</template>

<script>
export default {
  computed: {
    slots() {
      const count = this.$slots.default.length;
      const rows = Math.ceil(count / 6);
      const slots = [];
      for (let i = 0; i < rows; i++) {
        slots.push(this.$slots.default.slice(i * 6, (i + 1) * 6));
      }
      return slots;
    }
  }
};
</script>

<style>
.container {
  display: flex;
  flex-direction: column;
}

.row {
  display: flex;
  flex-wrap: wrap;
}

.slot {
  width: 16.6%;
  margin-right: 1%;
  margin-bottom: 1%;
}
</style>

在上述代码中,首先通过计算属性获取插槽数量,然后根据数量计算出需要多少行,以及每一行应该包含多少个插槽。接下来,将插槽按照每一行的个数进行切割,得到一个二维数组 slots。最后,使用 v-for 指令依次渲染每一行的插槽,并动态绑定样式。

这样就可以根据插槽的数量来动态布局了。


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

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