基于 CSS Grid 实现的网格布局组件,提供强大的二维布局能力,支持响应式设计和灵活的配置选项。
# 基本用法
元素1
元素2
元素3
元素4
元素5
元素6
复制代码
# 属性说明
| 属性 | 类型 | 默认值 | 可选值 | 说明 |
|---|---|---|---|---|
columns | String / Array / Number | 1fr | - | 列配置,支持数字、字符串或数组 |
rows | String / Array | auto | - | 行配置 |
gap | String | - | - | 网格间距(同时控制行和列) |
rowGap | String | - | - | 行间距 |
colGap | String | - | - | 列间距 |
flow | String | row | row、column、row dense、column dense | 自动排列方向 |
areas | String / Array | - | - | 命名区域布局 |
align | String | stretch | start、end、center、stretch、baseline | 子项对齐方式 |
justify | String | start | start、end、center、space-between、space-around、space-evenly、stretch | 内容对齐方式 |
responsive | Object | {} | - | 响应式断点配置 |
# XtGridItem 子项组件
配合 XtGridBox 使用的子项组件,支持跨行跨列等高级布局。
# 属性说明
| 属性 | 类型 | 默认值 | 可选值 | 说明 |
|---|---|---|---|---|
span | Number | 1 | >1 | 跨列数 |
rowSpan | Number | 1 | >1 | 跨行数 |
start | Number | 0 | >0 | 起始列位置 |
rowStart | Number | 0 | >0 | 起始行位置 |
area | String | - | - | 命名区域名称 |
justifySelf | String | auto | auto、start、end、center、stretch | 水平对齐 |
alignSelf | String | auto | auto、start、end、center、stretch、baseline | 垂直对齐 |
# 示例
# 基础网格
1
2
3
4
5
6
7
8
复制代码
# 列配置方式
1
2
3
固定宽度
弹性1
弹性2
固定
1份
2份
复制代码
# 跨列跨行
复制代码
# 命名区域布局
复制代码
# 对齐方式
居中
居中
居中
左
中
右
复制代码
# 独立间距控制
1
2
3
4
5
6
复制代码
# 自动填充布局
项目1
项目2
项目3
项目4
项目5
项目6
项目7
项目8
复制代码
# 嵌套网格
左侧面板
子项1
子项2
右侧面板
A
B
C
D
复制代码
# 常见布局问题解决方案
# 1. 网格内容溢出
问题:当网格内容过多时,网格会超出容器边界
解决方案:
<template>
<XtGridBox :columns="3" gap="12px" style="min-height: 0;">
<div style="overflow-y: auto; max-height: 200px;">
<!-- 大量内容 -->
</div>
</XtGridBox>
</template>
# 2. 动态内容高度不一致
问题:网格子项内容高度不同导致布局错乱
解决方案:
<template>
<!-- 使用 align 属性强制对齐 -->
<XtGridBox :columns="3" gap="12px" align="stretch">
<div style="display: flex; flex-direction: column;">
<div style="flex: 1;">内容区域</div>
<div>固定底部</div>
</div>
</XtGridBox>
</template>
# 3. 响应式列数调整
问题:在不同屏幕尺寸下需要不同的列数
解决方案:
<template>
<!-- 使用 CSS 类配合媒体查询 -->
<XtGridBox class="responsive-grid" gap="12px">
<div v-for="i in 6" :key="i" style="padding: 12px; background: #f0f0f0;">{{ i }}</div>
</XtGridBox>
</template>
<style>
.responsive-grid {
grid-template-columns: repeat(1, 1fr);
}
@media (min-width: 576px) {
.responsive-grid {
grid-template-columns: repeat(2, 1fr);
}
}
@media (min-width: 768px) {
.responsive-grid {
grid-template-columns: repeat(3, 1fr);
}
}
</style>
# 4. 网格项无法收缩
问题:当父容器高度受限,子项无法自动收缩
解决方案:
<template>
<div style="height: 300px; background: #f0f0f0;">
<XtGridBox :columns="2" style="height: 100%; min-height: 0;">
<div style="overflow-y: auto;">
<!-- 可滚动内容 -->
</div>
<div>固定内容</div>
</XtGridBox>
</div>
</template>
# 注意事项
- min-height: 0:当网格作为子元素嵌套在其他布局中时,建议设置
min-height: 0以确保正确的收缩行为 - 响应式设计:建议配合 CSS 媒体查询实现响应式布局
- 性能优化:对于大量网格项,考虑使用
flow="dense"优化空间利用率 - 嵌套使用:网格可以嵌套使用,但注意控制嵌套层级以避免性能问题