Vue.js 动态 Slot 展示:实现每行 6 个 Slot 的布局
<template>
<div>
<div v-for='(row, index) in rows' :key='index'>
<slot v-for='column in row' :key='column'></slot>
</div>
</div>
</template>
<script>
export default {
computed: {
rows() {
const slots = this.$slots.default || [];
const rows = [];
let row = [];
for (let i = 0; i < slots.length; i++) {
row.push(slots[i]);
if (row.length === 6 || i === slots.length - 1) {
rows.push(row);
row = [];
}
}
return rows;
},
},
};
</script>
<p>在这个组件中,我们首先通过计算属性 <code>rows</code> 计算出需要展示的行数和每行对应的 slot 数组。然后在模板中使用 <code>v-for</code> 来遍历每行和每行中的 slot,并使用 <code>key</code> 属性来标识每个元素。最终的效果就是将传入的 slot 按照每行 6 个的方式展示出来,并且能够动态处理不同数量的 slot。</p>
原文地址: https://www.cveoy.top/t/topic/lKFt 著作权归作者所有。请勿转载和采集!