介绍
Vant 是一个轻量、可靠的移动端组件库,于 2017 年开源。
目前 Vant 官方提供了 Vue 2 版本、Vue 3 版本和微信小程序版本,并由社区团队维护 React 版本和支付宝小程序版本。
当前版本:
Vant 3.x 版本 适用于 Vue 3 开发。
浏览器支持:
Vant 2 支持现代浏览器以及 Android >= 4.0、iOS >= 8.0。
Vant 3/4 支持现代浏览器以及 Chrome >= 51、iOS >= 10.0(与 Vue 3 一致)。
项目搭建
技术栈:
vue3.2(setup) + ts + vue-router@4 + pinia + vite + axios + vant3
初始化项目:
npm init vue@latest
配置项目:
✔ Project name: … <your-project-name>
✔ Add TypeScript? … No / Yes
× Add JSX Support? … No / Yes
✔ Add Vue Router for Single Page Application development? … No / Yes
✔ Add Pinia for state management? … No / Yes
× Add Vitest for Unit testing? … No / Yes
× Add Cypress for both Unit and End-to-End testing? … No / Yes
✔ Add ESLint for code quality? … No / Yes
✔ Add Prettier for code formatting? … No / Yes
Scaffolding project in ./<your-project-name>...
Done.
安装依赖:
npm i
安装插件vant
npm i vant
按需导入
npm i unplugin-vue-components -D
配置文件
如果是基于 vite 的项目,在 vite.config.js 文件中配置插件:
import Components from 'unplugin-vue-components/vite';
import { VantResolver } from 'unplugin-vue-components/resolvers';
Components({
resolvers: [VantResolver()],
}),
设置移动端适配
npm i postcss-px-to-viewport -D
安装vuex
npm i vuex@next -s
持久化存储
npm i vuex-persistedstate -s
重置样式
npm install normalize.css
引入重置样式
import 'normalize.css'
函数组件的样式
Vant 中有个别组件是以函数的形式提供的,包括 Toast,Dialog,Notify 和 ImagePreview 组件。在使用函数组件时,unplugin-vue-components 无法自动引入对应的样式,因此需要手动引入样式。
// main.ts
import 'vant/es/toast/style'
import 'vant/es/dialog/style';
import 'vant/es/notify/style';
import 'vant/es/image-preview/style';