Skip to content

Space 间距 - Vant 4

Space 间距

介绍

设置元素之间的间距。

引入

通过以下方式来全局注册组件,更多注册方式请参考组件注册

js
import { createApp } from'vue'; import { Space } from'vant'; const app = createApp(); app.use(Space);

🎯 代码演示

📐 基础用法

Space 组件会在各个子组件之间设置一定的间距,默认间距为 8px,让你的布局更加整齐美观。

html
<template>
  <van-space>
    <van-button type="primary">按钮</van-button>
    <van-button type="primary">按钮</van-button>
    <van-button type="primary">按钮</van-button>
  </van-space>
</template>

📱 垂直排列

direction 属性设置为 vertical,可以设置垂直方向排列的间距,适合纵向布局场景。

html
<template>
  <van-space direction="vertical" fill>
    <van-button type="primary" block>按钮</van-button>
    <van-button type="success" block>按钮</van-button>
    <van-button type="warning" block>按钮</van-button>
  </van-space>
</template>

🎨 自定义间距

通过调整 size 的值来控制间距的大小。传入 number 类型时,会默认使用 px 单位;也可以传入 string 类型,比如 2rem5vw 等带有单位的值。

html
<template>
  <div>
    <van-space :size="2">
      <van-button type="primary">小间距</van-button>
      <van-button type="primary">小间距</van-button>
    </van-space>
    
    <van-space :size="20">
      <van-button type="success">大间距</van-button>
      <van-button type="success">大间距</van-button>
    </van-space>
    
    <van-space size="2rem">
      <van-button type="warning">自定义单位</van-button>
      <van-button type="warning">自定义单位</van-button>
    </van-space>
  </div>
</template>

🎯 对齐方式

通过调整 align 的值来设置子元素的对齐方式,可选值为 startcenterendbaseline,在水平模式下的默认值为 center

html
<template>
  <div>
    <van-field v-model="align" label="对齐方式" />
    <van-space :align="align">
      <van-button type="primary">按钮</van-button>
      <div style="padding: 40px 20px; background: #f7f8fa;">高度不同的元素</div>
      <van-button type="success">按钮</van-button>
    </van-space>
  </div>
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    const align = ref('center');
    
    return {
      align,
    };
  },
};
</script>

🔄 自动换行

在水平模式下,通过 wrap 属性来控制子元素是否自动换行,适合响应式布局。

html
<template>
  <van-space wrap>
    <van-button type="primary">按钮 1</van-button>
    <van-button type="success">按钮 2</van-button>
    <van-button type="warning">按钮 3</van-button>
    <van-button type="danger">按钮 4</van-button>
    <van-button type="primary">按钮 5</van-button>
    <van-button type="success">按钮 6</van-button>
  </van-space>
</template>

📋 API

🎛️ Props

参数说明类型默认值
direction📐 间距方向*verticalhorizontal*
size📏 间距大小,如 20px2em,默认单位为 px,支持数组形式来分别设置横向和纵向间距*numberstring
align🎯 设置子元素的对齐方式*startend
wrap🔄 是否自动换行,仅适用于水平方向排列booleanfalse
fill📦 是否让 Space 变为一个块级元素,填充整个父元素booleanfalse

🎭 Slots

名称说明
default📦 间距组件内容

📘 类型定义

组件导出以下类型定义,方便在 TypeScript 项目中使用:

ts
import type { SpaceProps, SpaceSize, SpaceAlign } from 'vant';

📚 相关文档

📐 布局组件

🎨 展示组件

🎛️ 表单组件

🔧 工具组件

基於Vant構建的企業級移動端解決方案