在现有项目中使用 Vant 时,可以通过 npm 或 yarn 进行安装:
- # Vue 2 项目,安装 Vant 2:
- npm i vant -S
-
- # Vue 3 项目,安装 Vant 3:
- npm i vant@next -S
1、全局引入 (注意: 配置按需引入后,将不允许直接导入所有组件)
Vant 支持一次性导入所有组件,引入所有组件会增加代码包体积,因此不推荐这种做法。
- // 在src/main.js进行全局引入
- import Vant from 'vant'
- import 'vant/lib/index.css';
- Vue.use(Vant)
2.自动按需引入组件 (推荐)
babel-plugin-import是一款 babel 插件,它会在编译过程中将 import 的写法自动转换为按需引入的方式。
- # 安装插件
- npm i babel-plugin-import -D
- // 在.babelrc 中添加配置
- // 注意:webpack 1 无需设置 libraryDirectory
- {
- "plugins": [
- ["import", {
- "libraryName": "vant",
- "libraryDirectory": "es",
- "style": true
- }]
- ]
- }
-
- // 对于使用 babel7 的用户,可以在 babel.config.js 中配置
- module.exports = {
- plugins: [
- ['import', {
- libraryName: 'vant',
- libraryDirectory: 'es',
- style: true
- }, 'vant']
- ]
- };
最后,在main.js中
- import {Button} from 'vant'
- Vue.use(Button)
- // 引入的多的话
- import { Button, Row, Col } from 'vant'
- Vue.use(Button).use(Row).use(Col)
3、如果想在页面中单独使用组件
- import { Button, Row, Col } from 'vant'
- export default{
- components: {
- [Button.name]:Button // 有的组件有专门的引入方式,比如Dialog,可以看看
- }
- }