A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

1、按需引入

1. 借助 babel-plugin-component,我们可以只引入需要的组件,以达到减小项目体积的目的:

        npm install babel-plugin-component -D
1
2. 更改.babelrc文件

        "plugins": [
    [
      "component",
      {
        "libraryName": "element-ui",
        "styleLibraryName": "theme-chalk"
      }
    ]
  ]
1
2
3
4
5
6
7
8
9
当然这里如果有其他的配置,只需要在 plugins 的数组中继续添加我们需要的配置代码就行了
2、 我们将按需引入的代码单独分割一下

1. 在 src 文件夹中新建我们的 element 文件夹,并在里面新建一个 index.js 文件



2. 在index文件中去书写我们需要引入的部分组件

// 导入自己需要的组件
import { Select, Option, OptionGroup, Input, Tree, Dialog, Row, Col } from 'element-ui'
const element = {
  install: function (Vue) {
    Vue.use(Select)
    Vue.use(Option)
    Vue.use(OptionGroup)
    Vue.use(Input)
    Vue.use(Tree)
    Vue.use(Dialog)
    Vue.use(Row)
    Vue.use(Col)
  }
}
export default element
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
这里要使用 Select 组件,必须同时使用 Option 和 OptionGroup
这里的 install 方法表示在 main.js 中,如果使用 Vue.use() 方法的话,则该方法默认会调用 install 方法
3. 在 main.js 中使用该文件,就大功告成了

        // css样式还是需要全部引入
        import 'element-ui/lib/theme-chalk/index.css'
        import element from './element/index'
        Vue.use(element)
1
2
3
4
3、为什么要使用 单独分割的方式去按需加载

1. 我们使用常规的方式再来加载一次

在 main.js 文件中 直接使用
import 'element-ui/lib/theme-chalk/index.css'
import { Dialog, Select, Option, OptionGroup, Input, Tree, Row, Col } from 'element-ui'
Vue.use(Select)
Vue.use(Option)
Vue.use(OptionGroup)
Vue.use(Input)
Vue.use(Tree)
Vue.use(Dialog)
Vue.use(Row)
Vue.use(Col)
1
2
3
4
5
6
7
8
9
10
不好意思,现在就报错了


我们在 element-ui 的源码中可以看到,的确使用的是 Dialog,但是我们在运行的时候还是报错了


2. 我们将引入的 Dialog 做一些修改,如下图


---------------------
转载,仅作分享,侵删
作者:hi修修
原文:https://blog.csdn.net/li522021642/article/details/82851246


1 个回复

正序浏览
奈斯
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马