1、介绍
Vant 是一个轻量、可靠的移动端组件库,于 2017 年开源。
目前 Vant 官方提供了 Vue 2 版本、Vue 3 版本和微信小程序版本,并由社区团队维护 React 版本和支付宝小程序版本。
2、安装
1 # Vue 3 项目,安装最新版 Vant: 2 npm i vant -S 3 4 # Vue 2 项目,安装 Vant 2: 5 npm i vant@latest-v2 -S
3、项目引入
创建vue项目,然后在main.js中引入vant组件
方式一. 自动按需引入组件 (推荐)
babel-plugin-import 是一款 babel 插件,它会在编译过程中将 import 的写法自动转换为按需引入的方式。
1 # 安装插件 2 npm i babel-plugin-import -D
配置
1 // 在.babelrc 中添加配置 2 // 注意:webpack 1 无需设置 libraryDirectory 3 { 4 "plugins": [ 5 ["import", { 6 "libraryName": "vant", 7 "libraryDirectory": "es", 8 "style": true 9 }] 10 ] 11 } 12 13 // 对于使用 babel7 的用户,可以在 babel.config.js 中配置 14 module.exports = { 15 plugins: [ 16 ['import', { 17 libraryName: 'vant', 18 libraryDirectory: 'es', 19 style: true 20 }, 'vant'] 21 ] 22 };
方式二. 手动按需引入组件
1 import Button from 'vant/lib/button'; 2 import 'vant/lib/button/style';
方式三. 导入所有组件
Vant 支持一次性导入所有组件,引入所有组件会增加代码包体积,因此不推荐这种做法
1 import Vue from 'vue'; 2 import Vant from 'vant'; 3 import 'vant/lib/index.css'; 4 5 Vue.use(Vant);
4、组件注册
全局注册
全局注册后,你可以在 app 下的任意子组件中使用注册的 Vant 组件。
1 import Vue from 'vue'; 2 import { Button } from 'vant'; 3 4 // 方式一. 通过 Vue.use 注册 5 // 注册完成后,在模板中通过 <van-button> 或 <VanButton> 标签来使用按钮组件 6 Vue.use(Button); 7 8 // 方式二. 通过 Vue.component 注册 9 // 注册完成后,在模板中通过 <van-button> 标签来使用按钮组件 10 Vue.component(Button.name, Button);
局部注册
局部注册后,你可以在当前组件中使用注册的 Vant 组件。
1 import { Button } from 'vant'; 2 3 export default { 4 components: { 5 [Button.name]: Button, 6 }, 7 };
4、使用
main.js内容
1 import Vue from 'vue' 2 import App from './App.vue' 3 4 // 导入组件 5 import Vant from 'vant' 6 // 导入组件样式库 7 import 'vant/lib/index.css' 8 // 全局注册vant 9 Vue.use(Vant) 10 11 Vue.config.productionTip = false 12 13 new Vue({ 14 render: h => h(App) 15 }).$mount('#app')
在App.vue中使用相关组件
1 <template> 2 <div class="app"> 3 <van-button type="primary">主要按钮</van-button> 4 <van-button type="info">信息按钮</van-button> 5 <van-button type="default">默认按钮</van-button> 6 <van-button type="warning">警告按钮</van-button> 7 <van-button type="danger">危险按钮</van-button> 8 </div> 9 </template> 10 <script> 11 export default { 12 } 13 </script> 14 <style> 15 </style>
启动服务,查看样式加载情况,npm run serve
标签:01,Vant,Button,Vue,组件,import,vant From: https://www.cnblogs.com/wang1001/p/18121803