一、vant简介
Vant 是一个轻量、可靠的移动端组件库,于 2017 年开源。
目前 Vant 官方提供了 Vue 2 版本、Vue 3 版本和微信小程序版本,并由社区团队维护 React 版本和支付宝小程序版本。
里面的快速上手的教程,适用于小程序的软件,但是vscode的vant组件安装看着官网,我本人有点操作不过来,后面自己研究了一下,安装完,想着可能也会有些同学不太会,接下来我把安装步骤写出来。
二、安装
(1)下载
在你的 Vue 项目根目录下,使用 npm 或 yarn 安装 Vant:
这种是安装vue3最新的版本
npm install vant --save
或者 yarn add vant
安装vue2最新版本npm install vant@latest-v2
yarn add vantt@latest-v2
vant现在好像不支持全局引 入,这边我就介绍局部引入
(2)局部引入
如果你只想在特定的组件中使用 Vant 组件,可以按需引入。首先安装 **babel-plugin-import
**以支持按需加载。
npm install babel-plugin-import --save-dev
或者 yarn add babel-plugin-import --dev
然后在你的 Babel 配置文件(通常是 .babelrc
或**babel.config.js
**)中添加插件配置:

javascript
module.exports = {
presets: [
'@vue/cli-plugin-babel/preset'
],
plugins: [
[
"import",
{
libraryName: "vant",
libraryDirectory: "es",
style: true
}
]
]
};
(3)案例
简单的写了个页面,可以参考具体是怎么使用的
javascript
<template>
<div class="user-info">
<van-cell-group>
<van-cell title="用户名" :value="userInfo.username" />
<van-field
v-model="userInfo.email"
title="邮箱"
placeholder="请输入邮箱"
@blur="validateEmail"
/>
<van-field
v-model="userInfo.phone"
type="number"
title="手机号"
placeholder="请输入手机号"
@blur="validatePhone"
/>
<van-switch v-model="userInfo.isActive" title="激活状态" />
</van-cell-group>
<div class="actions">
<van-button type="primary" @click="saveUserInfo">保存</van-button>
</div>
</div>
</template>
<script>
import { Button,Field,CellGroup,Cell,Switch } from 'vant';
export default {
components: {
'van-button': Button,
'van-field': Field,
'van-cell-group': CellGroup,
'van-cell': Cell,
'van-switch': Switch,
},
data() {
return {
userInfo: {
username: '张三',
email: '',
phone: '',
isActive: true,
},
emailError: '',
phoneError: '',
};
},
methods: {
validateEmail() {
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
this.emailError = !emailPattern.test(this.userInfo.email) ? '邮箱格式不正确' : '';
},
validatePhone() {
const phonePattern = /^[1][3-9]\d{9}$/;
this.phoneError = !phonePattern.test(this.userInfo.phone) ? '手机号格式不正确' : '';
},
saveUserInfo() {
this.validateEmail();
this.validatePhone();
if (!this.emailError && !this.phoneError) {
// 在这里处理保存用户信息的逻辑,比如发送到服务器
console.log('保存的用户信息:', this.userInfo);
alert('用户信息已保存');
} else {
alert('请检查邮箱和手机号格式');
}
},
},
};
</script>
<style scoped>
.user-info {
padding: 16px;
}
.actions {
margin-top: 16px;
text-align: right;
}
</style>
效果:
