liveh5-nuxt/app/components/waterfallFlow/index.vue
xingyy 0761ea8ab0 feat(components): 添加瀑布流布局组件
- 新增 waterfallFlow 组件,支持多列自适应高度的瀑布流布局
- 组件使用 Vue 3 的 composition API,包括 ref、onMounted 和 watch
- 提供灵活的自定义插槽,允许用户自定义每个项目的样式和内容
- 默认样式采用 flex 布局,支持自定义样式
2025-02-14 15:44:29 +08:00

78 lines
1.4 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<template>
<div class="waterfall-container" ref="container">
<div
v-for="(column, columnIndex) in columns"
:key="columnIndex"
class="waterfall-column"
:style="{ width: `${100 / columnCount}%` }"
>
<div
v-for="item in column"
:key="item.id"
class="waterfall-item"
>
<!-- 默认插槽传入当前item数据 -->
<slot :item="item">
</slot>
</div>
</div>
</div>
</template>
<script setup>
import { ref, onMounted, watch } from 'vue'
const props = defineProps({
items: {
type: Array,
required: true
},
columnCount: {
type: Number,
default: 2
}
})
const columns = ref([])
// 计算每列的内容
const calculateColumns = () => {
const cols = Array.from({ length: props.columnCount }, () => [])
props.items.forEach((item, index) => {
// 将项目添加到高度最小的列中
const columnIndex = index % props.columnCount
cols[columnIndex].push(item)
})
columns.value = cols
}
// 监听items变化重新计算列
watch(() => props.items, () => {
calculateColumns()
}, { deep: true })
onMounted(() => {
calculateColumns()
})
</script>
<style scoped>
.waterfall-container {
display: flex;
width: 100%;
gap: 16px;
}
.waterfall-column {
display: flex;
flex-direction: column;
gap: 16px;
}
.waterfall-item {
break-inside: avoid;
}
/* 默认样式可以移到使用组件时自定义 */
</style>