使用Vue实现瀑布流布局
Reverse Lv4

概述

瀑布流布局相比栅格网格不同的就是,只要卡片塞的合理,一般是不会出现空格。

不像栅格,只能做水平对齐,但是如果卡片的高度不能统一,那就会出现很多空白的区域,影响美观。

安装包

vue 里面vue-masonry-wall就是用来做瀑布样式的,可以直接安装引入。

安装之前先注意,如果你是vue2版本的话可能是要用npm install vue-masonry-wall这个。

下面这个是vue3的安装,实际上我测试过在vue3里面直接执行pnpm install vue-masonry-wall,并且使用。

会出现API 兼容性问题,导致出现错误,所以我猜测这两个应该是分为 vue3 和 vue2 两个版本使用的。

1
2
3
yarn add @yeger/vue-masonry-wall

npm install @yeger/vue-masonry-wall

示例代码

全局引入

1
2
3
4
5
6
import { createApp } from "vue";
import MasonryWall from "@yeger/vue-masonry-wall";

const app = createApp();

app.use(MasonryWall);

组件内使用

:::warning 建议
值得注意的是当数据量比较大时渲染压力会增加,建议做分页来缓解前端的渲染压力
:::

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<template>
<masonry-wall :items="items" :column-width="300" :gap="16">
<template #default="{ item }">
<div class="item">
<img : src="item.image" :alt="item.title" >
<h3>{{ item.title }}</h3>
<p>{{ item.description }}</p>
</div>
</template>
</masonry-wall>
</template>

<script setup>
import { ref } from "vue";

const items = ref([
{
id: 1,
title: "标题1",
description: "描述1",
image: "图片地址1",
},
// ... 更多数据
]);
</script>

<style scoped>
.item {
background: #fff;
border-radius: 8px;
padding: 16px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.item img {
width: 100%;
height: auto;
border-radius: 4px;
}
</style>

配置选项

masonry-wall 组件支持以下主要配置:

  • items: 数组,必需,要显示的数据项
  • column-width: 数字,每列的宽度(像素)
  • gap: 数字,列之间的间距(像素)
  • rtl: 布尔值,是否从右到左布局
  • ssr-columns: 数字,服务器端渲染时的列数

响应式处理

为了在不同屏幕尺寸下获得最佳显示效果,可以使用计算属性动态设置列宽:

1
2
3
4
5
6
7
8
9
10
<script setup>
import { computed } from "vue";

const columnWidth = computed(() => {
const screenWidth = window.innerWidth;
if (screenWidth < 600) return 150;
if (screenWidth < 900) return 200;
return 300;
});
</script>