前端性能优化-按需引入Vant组件

一.安装

// 通过 npm 安装
npm i vant -S
// 通过 yarn 安装
yarn add vant

二.自动按需引入

  1. 安装插件
    babel-plugin-import 是一款 babel 插件,它会在编译过程中将 import 的写法自动转换为按需引入的方式
npm i babel-plugin-import -D
  1. 配置

.babelrc 中添加配置,其中还有其他内容

"plugins": ["transform-vue-jsx", "transform-runtime"]

直接加在后面

"plugins": [
    "transform-vue-jsx", 
    "transform-runtime",
    ["import", {
    "libraryName": "vant",
    "libraryDirectory": "es",
    "style": true
    }]
]

三.使用

3.1 组件中按需引入

<template>
  <div>
     <van-button type="primary">主要按钮</van-button>
  </div>
</template>

<script>
import { Button } from "vant";

export default {
   components: { Button }, //写法错误
}
</script>

这样运行发现会报错
在这里插入图片描述
后来发现正确写法是

components: { [Button.name]: Button }

3.2 全局按需引入

新建vant.js文件,我的文件放在了utils下,看你喜欢放在哪里

import Vue from 'vue'
// 在这里引入你所需的组件
import {
  Button, //按钮
  Toast, //轻提示
  Swipe, //轮播图
  SwipeItem,
  Area, //省市区选择
  Popup, //弹出层
  Field, //输入框
  Stepper, //步进器
  Cell, //单元格
  CellGroup,
  Divider //分割线
} from 'vant'

// 按需引入UI组件
Vue.use(Button)
Vue.use(Toast)
Vue.use(Swipe)
Vue.use(SwipeItem)
Vue.use(Area)
Vue.use(Popup)
Vue.use(Field)
Vue.use(Stepper)
Vue.use(Cell)
Vue.use(CellGroup)
Vue.use(Divider)

main.js文件把曾经引入的vantUI去除,加上按需引入的文件

// 引入vantUI库
// import Vant from 'vant';
// import 'vant/lib/index.css';
import * as vant from './utils/vant'

直接使用即可

<template>
  <div>
     <van-button type="primary">主要按钮</van-button>
  </div>
</template>

<script>
export default {
}
</script>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值