Vue.js 组件动态渲染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>
<p>在模板中,我们使用 v-for 遍历计算属性 rows,每一行有 6 个 slot,然后在每行中再使用 v-for 遍历 getSlotsInRow 方法获取这一行的 slot,同时设置 slot 的 name 为 'slot-' + i,这样就可以动态渲染 slot 了。</p>
<p>计算属性 slotCount 用于获取传入 slot 的数量,然后根据数量计算出应该有多少行,计算属性 rows 返回一个数组,包含每一行的起始下标。</p>
<p>方法 getSlotsInRow 用于根据行号获取这一行的 slot,slice 方法用于截取数组中的一部分。</p>
<p>最后,我们还需要设置一些样式,让每一行显示为一个 flex 容器,超出容器宽度时自动换行。</p>
原文地址: https://www.cveoy.top/t/topic/lKng 著作权归作者所有。请勿转载和采集!