Skip to content

快速开始

本指南将帮助您快速在项目中集成和使用Vant移动端UI组件库。

📦 安装

npm 安装

bash
npm install vant

yarn 安装

bash
yarn add vant

pnpm 安装

bash
pnpm add vant

🚀 引入组件

方式一:自动按需引入(推荐)

安装插件:

bash
npm install unplugin-vue-components -D

配置 vite.config.js

javascript
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import Components from 'unplugin-vue-components/vite'
import { VantResolver } from 'unplugin-vue-components/resolvers'

export default defineConfig({
  plugins: [
    vue(),
    Components({
      resolvers: [VantResolver()],
    }),
  ],
})

方式二:手动按需引入

javascript
import { createApp } from 'vue'
import { Button, Cell } from 'vant'

const app = createApp()
app.use(Button)
app.use(Cell)

方式三:完整引入

javascript
import { createApp } from 'vue'
import Vant from 'vant'
import 'vant/lib/index.css'

const app = createApp()
app.use(Vant)

💡 基础用法

第一个组件

vue
<template>
  <div>
    <van-button type="primary">主要按钮</van-button>
    <van-button type="success">成功按钮</van-button>
  </div>
</template>

移动端适配

在HTML头部添加viewport meta标签:

html
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, viewport-fit=cover">

Rem适配

安装postcss-pxtorem:

bash
npm install postcss-pxtorem -D

配置 postcss.config.js

javascript
module.exports = {
  plugins: {
    'postcss-pxtorem': {
      rootValue: 37.5,
      propList: ['*'],
    },
  },
}

🎨 主题定制

CSS变量定制

css
:root {
  --van-primary-color: #1989fa;
  --van-success-color: #07c160;
  --van-danger-color: #ee0a24;
  --van-warning-color: #ff976a;
  --van-text-color: #323233;
  --van-active-color: #f2f3f5;
  --van-active-opacity: 0.7;
  --van-disabled-opacity: 0.5;
  --van-background-color: #f7f8fa;
  --van-background-color-light: #fafafa;
}

Less变量定制

less
@primary-color: #1989fa;
@success-color: #07c160;
@danger-color: #ee0a24;
@warning-color: #ff976a;
@text-color: #323233;
@border-color: #ebedf0;
@active-color: #f2f3f5;
@background-color: #f7f8fa;
@background-color-light: #fafafa;

📱 移动端调试

在桌面端调试

安装 @vant/touch-emulator:

bash
npm install @vant/touch-emulator -D

引入模拟器:

javascript
import '@vant/touch-emulator'

真机调试

  1. 确保手机和电脑在同一网络
  2. 启动开发服务器
  3. 在手机浏览器中访问电脑IP地址

🔧 TypeScript支持

Vant完全支持TypeScript,无需额外配置:

typescript
import { Button } from 'vant'
import type { ButtonType } from 'vant'

const buttonType: ButtonType = 'primary'

🌍 国际化

引入语言包

javascript
import { Locale } from 'vant'
import enUS from 'vant/es/locale/lang/en-US'

Locale.use('en-US', enUS)

支持的语言

  • 简体中文 (zh-CN)
  • 繁体中文 (zh-TW)
  • 英语 (en-US)
  • 德语 (de-DE)
  • 日语 (ja-JP)
  • 等30+种语言

⚡ 性能优化

按需引入

只引入使用的组件,减小打包体积:

javascript
import { Button, Cell } from 'vant'

图片懒加载

使用Lazyload指令:

javascript
import { Lazyload } from 'vant'

app.use(Lazyload)
vue
<template>
  <img v-lazy="imageUrl" />
</template>

🚀 下一步

💬 获得帮助

基于Vant构建的企业级移动端解决方案