一、方式一:全量引入 Element UI
全量引入即一次性加载 Element UI 所有组件和样式,优点是配置简单,适合快速开发;缺点是打包体积较大,生产环境可能存在冗余。
1. 安装 Element UI
全量引入只需安装 Element UI 核心依赖(运行时必需,用-S
或默认不写参数):
npm install element-ui -S
2. 配置全量引入(main.js)
在项目入口文件main.js
中引入所有组件和样式,并全局注册:
import Vue from 'vue'
import App from './App.vue'
// 1. 全量引入Element UI组件和样式
import ElementUI from 'element-ui' // 引入所有组件
import 'element-ui/lib/theme-chalk/index.css' // 引入所有样式
// 2. 全局注册Element UI(注册后所有组件可直接在模板使用)
Vue.use(ElementUI)
Vue.config.productionTip = false
new Vue({
render: h => h(App),
}).$mount('#app')
二、方式二:按需引入 Element UI(生产环境首选)
按需引入仅加载项目中用到的组件和对应样式,能显著减小打包体积,是生产环境的最佳实践。但需额外配置 Babel 插件。
1. 安装依赖
需安装两个依赖:
element-ui
:核心组件库(运行时必需,-S
);babel-plugin-component
:按需引入插件(仅开发时用,-D
);
# 安装核心组件库(运行时必需)
npm install element-ui -S
# 安装按需引入插件(开发时用)
npm install babel-plugin-component -D
2. 配置 Babel(babel.config.js)
在项目根目录的babel.config.js
中添加插件配置,让 Babel 自动处理组件和样式的按需加载:
module.exports = {
presets: [
'@vue/cli-plugin-babel/preset' // Vue CLI默认预设,无需修改
],
plugins: [
[
'component', // 对应安装的babel-plugin-component插件
{
libraryName: 'element-ui', // 指定目标组件库为Element UI
styleLibraryName: 'theme-chalk' // 指定Element UI的样式主题(默认theme-chalk)
}
]
]
}
3. 按需引入组件(main.js)
在main.js
中仅引入项目用到的组件(本文示例用Button
、DatePicker
、Row
),并全局注册:
import Vue from 'vue'
import App from './App.vue'
// 1. 按需引入Element UI组件(仅引入用到的组件)
import { Button, DatePicker, Row } from 'element-ui'
// 2. 全局注册组件(两种方式二选一,效果一致)
// 方式A:用Vue.component(显式指定组件名,Button.name即"el-button")
Vue.component(Button.name, Button)
Vue.component(DatePicker.name, DatePicker)
Vue.component(Row.name, Row)
// 方式B:用Vue.use(组件内部已封装install方法,自动注册)
// Vue.use(Button)
// Vue.use(DatePicker)
// Vue.use(Row)
Vue.config.productionTip = false
new Vue({
render: h => h(App),
}).$mount('#app')
三、组件代码(App.vue)
<template>
<div>
<el-row>
<el-button type="primary">按钮</el-button>
<el-button type="primary" plain>按钮</el-button>
<el-button type="primary" round>按钮</el-button>
<el-button type="primary" circle>按钮</el-button>
</el-row>
<el-date-picker
v-model="date"
type="date"
placeholder="选择日期"
value-format="yyyy-MM-dd">
</el-date-picker>
</div>
</template>
<script>
export default {
name:'App',
data(){
return {
date:""
}
},
components:{
}
}
</script>
<style>
</style>
四、关键知识点解析
1. -D
和-S
的区别(依赖分类)
-S
(--save
,默认):安装到dependencies
(生产环境依赖),即项目运行时必须的依赖(如element-ui
,用户使用时需要);-D
(--save-dev
):安装到devDependencies
(开发环境依赖),即仅开发时用的工具(如babel-plugin-component
,打包后无需包含)。
错误后果:若将babel-plugin-component
用-S
安装,会导致生产环境打包时包含无用的开发工具,增加体积。
2. Vue.use()
和Vue.component()
的区别
两种方法都能全局注册组件,但适用场景不同:
Vue.component(组件名, 组件对象)
:直接注册 “单个组件”,需手动指定组件名(如Vue.component('el-button', Button)
);Vue.use(插件/组件)
:用于安装 “带install
方法的对象”(Element UI 组件内部已封装install
方法,调用Vue.use
时会自动注册组件)。
本文示例中:Button
组件既可以用Vue.component(Button.name, Button)
注册,也可以用Vue.use(Button)
注册,效果完全一致。
五、总结
引入方式 | 优点 | 缺点 | 适用场景 |
---|---|---|---|
全量引入 | 配置简单,无需额外插件 | 打包体积大,冗余代码多 | 快速开发、小型项目 |
按需引入 | 打包体积小,性能优 | 需配置 Babel 插件,步骤稍多 | 生产环境、中大型项目 |