
前言
在移动端开发日益重要的今天,选择一个优秀的 UI 组件库可以极大提升开发效率。Vant 作为有赞团队开源的移动端 Vue 组件库,凭借其轻量、可靠的特性,成为了众多开发者的首选。本文将深入介绍 Vant 的特性、使用方法以及实战应用。
什么是 Vant?
Vant 是有赞前端团队开源的移动端组件库,于 2017 年首次发布。它基于 Vue.js 框架,专门为移动端场景设计,提供了丰富的基础组件和业务组件。
核心特性
- 🚀 性能极佳:组件平均体积小于 1KB(min+gzip)
- 🎨 组件丰富:提供 65+ 个高质量组件,覆盖移动端各种场景
- 💪 TypeScript 支持:使用 TypeScript 构建,提供完整的类型定义
- 🌍 国际化:支持多语言,内置 30+ 种语言包
- 📱 移动端优化:专为移动端设计,支持触摸手势
- 🛠️ 按需引入:支持 Tree Shaking,只打包使用的组件
快速开始
安装
# 通过 npm 安装
npm install vant
# 通过 yarn 安装
yarn add vant
# 通过 pnpm 安装
pnpm add vant
引入方式
1. 全量引入
import { createApp } from 'vue'
import Vant from 'vant'
import 'vant/lib/index.css'
const app = createApp()
app.use(Vant)
2. 按需引入(推荐)
import { Button, Cell } from 'vant'
import 'vant/lib/button/style'
import 'vant/lib/cell/style'
const app = createApp()
app.use(Button).use(Cell)
3. 自动按需引入
使用 unplugin-vue-components 插件:
// vite.config.js
import { defineConfig } from 'vite'
import Components from 'unplugin-vue-components/vite'
import { VantResolver } from 'unplugin-vue-components/resolvers'
export default defineConfig({
plugins: [
Components({
resolvers: [VantResolver()],
}),
],
})
核心组件详解
1. 基础组件
Button 按钮
<template>
<!-- 基础用法 -->
<van-button type="primary">主要按钮</van-button>
<van-button type="success">成功按钮</van-button>
<van-button type="default">默认按钮</van-button>
<van-button type="warning">警告按钮</van-button>
<van-button type="danger">危险按钮</van-button>
<!-- 尺寸 -->
<van-button size="large">大号按钮</van-button>
<van-button size="normal">普通按钮</van-button>
<van-button size="small">小型按钮</van-button>
<van-button size="mini">迷你按钮</van-button>
<!-- 状态 -->
<van-button loading>加载中...</van-button>
<van-button disabled>禁用状态</van-button>
</template>
Cell 单元格
<template>
<van-cell-group>
<van-cell title="单元格" value="内容" />
<van-cell title="单元格" value="内容" label="描述信息" />
<van-cell title="单元格" value="内容" is-link />
<van-cell title="单元格" value="内容" is-link to="/detail" />
</van-cell-group>
</template>
2. 表单组件
Field 输入框
<template>
<van-cell-group>
<van-field
v-model="value"
label="文本"
placeholder="请输入文本"
/>
<van-field
v-model="password"
type="password"
label="密码"
placeholder="请输入密码"
/>
<van-field
v-model="message"
rows="2"
autosize
label="留言"
type="textarea"
placeholder="请输入留言"
/>
</van-cell-group>
</template>
<script>
export default {
data() {
return {
value: '',
password: '',
message: ''
}
}
}
</script>
Picker 选择器
<template>
<van-picker
:columns="columns"
@change="onChange"
@confirm="onConfirm"
@cancel="onCancel"
/>
</template>
<script>
export default {
data() {
return {
columns: ['杭州', '宁波', '温州', '绍兴', '湖州', '嘉兴', '金华']
}
},
methods: {
onChange(picker, value, index) {
console.log(`当前值:${value}, 当前索引:${index}`)
},
onConfirm(value, index) {
console.log(`确认选择:${value}`)
},
onCancel() {
console.log('取消选择')
}
}
}
</script>
3. 反馈组件
Toast 轻提示
import { Toast } from 'vant'
// 文字提示
Toast('提示内容')
// 成功提示
Toast.success('成功文案')
// 失败提示
Toast.fail('失败文案')
// 加载提示
Toast.loading({
message: '加载中...',
forbidClick: true,
})
Dialog 弹出框
import { Dialog } from 'vant'
// 消息提示
Dialog.alert({
title: '标题',
message: '弹窗内容',
}).then(() => {
// on close
})
// 消息确认
Dialog.confirm({
title: '标题',
message: '弹窗内容',
})
.then(() => {
// on confirm
})
.catch(() => {
// on cancel
})
4. 展示组件
List 列表
<template>
<van-list
v-model:loading="loading"
:finished="finished"
finished-text="没有更多了"
@load="onLoad"
>
<van-cell
v-for="item in list"
:key="item"
:title="item"
/>
</van-list>
</template>
<script>
export default {
data() {
return {
list: [],
loading: false,
finished: false,
}
},
methods: {
onLoad() {
// 异步更新数据
setTimeout(() => {
for (let i = 0; i < 10; i++) {
this.list.push(this.list.length + 1)
}
this.loading = false
if (this.list.length >= 40) {
this.finished = true
}
}, 1000)
},
},
}
</script>
Swipe 轮播
<template>
<van-swipe :autoplay="3000" indicator-color="white">
<van-swipe-item>1</van-swipe-item>
<van-swipe-item>2</van-swipe-item>
<van-swipe-item>3</van-swipe-item>
<van-swipe-item>4</van-swipe-item>
</van-swipe>
</template>
主题定制
Vant 支持主题定制,可以通过 CSS 变量或 Less 变量进行样式覆盖。
CSS 变量定制
:root {
--van-primary-color: #07c160;
--van-success-color: #ee0a24;
--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 变量定制
// 在项目中创建 theme.less 文件
@primary-color: #1989fa;
@success-color: #07c160;
@danger-color: #ee0a24;
@warning-color: #ff976a;
@text-color: #323233;
@active-color: #f2f3f5;
@active-opacity: 0.7;
@disabled-opacity: 0.5;
@background-color: #f7f8fa;
@background-color-light: #fafafa;
项目实践
1. 项目结构组织
src/
├── components/
│ ├── common/ # 公共组件
│ └── business/ # 业务组件
├── views/
│ ├── home/ # 首页
│ ├── product/ # 产品页
│ └── user/ # 用户页
├── utils/
│ ├── request.js # 请求封装
│ └── vant.js # Vant 配置
└── styles/
├── index.css # 全局样式
└── variables.css # CSS 变量
2. 组件封装
<!-- components/common/SearchBar.vue -->
<template>
<div class="search-bar">
<van-search
v-model="searchValue"
:placeholder="placeholder"
show-action
@search="onSearch"
@cancel="onCancel"
>
<template #action>
<div @click="onSearch">搜索</div>
</template>
</van-search>
</div>
</template>
<script>
export default {
name: 'SearchBar',
props: {
placeholder: {
type: String,
default: '请输入搜索关键词'
}
},
data() {
return {
searchValue: ''
}
},
methods: {
onSearch() {
this.$emit('search', this.searchValue)
},
onCancel() {
this.searchValue = ''
this.$emit('cancel')
}
}
}
</script>
3. 性能优化
// utils/vant.js - 按需引入优化
import {
Button,
Cell,
CellGroup,
Field,
Toast,
Dialog
} from 'vant'
const components = [Button, Cell, CellGroup, Field]
export default {
install(app) {
components.forEach(component => {
app.use(component)
})
// 全局配置
app.config.globalProperties.$toast = Toast
app.config.globalProperties.$dialog = Dialog
}
}
与其他框架的对比
| 特性 | Vant | Ant Design Mobile | Mint UI |
|---|---|---|---|
| 框架支持 | Vue 2/3 | React | Vue 2 |
| 组件数量 | 65+ | 45+ | 50+ |
| 体积大小 | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ |
| TypeScript | ✅ | ✅ | ❌ |
| 维护状态 | 活跃 | 活跃 | 停止维护 |
| 社区生态 | 丰富 | 丰富 | 一般 |
实际应用场景
1. 电商应用
- 商品列表、详情页
- 购物车、订单流程
- 用户中心、地址管理
2. 资讯应用
- 文章列表、详情页
- 评论系统
- 用户互动功能
3. 工具应用
- 表单收集
- 数据展示
- 设置页面
常见问题及解决方案
1. 样式冲突
/* 使用命名空间隔离 */
.app-container {
/* Vant 组件样式只在此容器内生效 */
}
2. 按需引入失效
// 确保正确引入样式文件
import 'vant/lib/index.css'
// 或使用 babel-plugin-import
{
"plugins": [
["import", {
"libraryName": "vant",
"libraryDirectory": "es",
"style": true
}, "vant"]
]
}
3. 移动端适配
<!-- 确保添加 viewport meta 标签 -->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
// 使用 postcss-pxtorem 自动转换 px 到 rem
module.exports = {
plugins: {
'postcss-pxtorem': {
rootValue: 37.5,
propList: ['*']
}
}
}
版本升级指南
Vue 2 到 Vue 3 迁移
// Vue 2 写法
import Vue from 'vue'
import Vant from 'vant'
Vue.use(Vant)
// Vue 3 写法
import { createApp } from 'vue'
import Vant from 'vant'
const app = createApp()
app.use(Vant)
Vant 2 到 Vant 3 主要变化
- 移除了部分过时组件
- API 命名更加规范
- 更好的 TypeScript 支持
- 性能优化和体积减小
总结
Vant 作为一个成熟的移动端 Vue 组件库,具有以下优势:
- 轻量高效:组件体积小,性能优秀
- 功能完善:覆盖移动端开发的各种场景
- 易于使用:API 设计简洁,上手容易
- 生态丰富:有完善的文档和社区支持
- 持续维护:有赞团队持续维护更新
对于需要快速开发移动端 Vue 应用的团队来说,Vant 是一个非常值得推荐的选择。它不仅能提高开发效率,还能保证应用的用户体验和性能表现。
相关资源
- 官方文档:https://vant-contrib.gitee.io/vant/
- GitHub 仓库:https://github.com/youzan/vant
- Vue 3 版本:https://vant-contrib.gitee.io/vant/next/
- Vant Weapp:https://vant-contrib.gitee.io/vant-weapp/

3039

被折叠的 条评论
为什么被折叠?



