一、方式一:全量引入 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 = falsenew 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 UIstyleLibraryName: '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 = falsenew 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-pickerv-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 插件,步驟稍多 | 生產環境、中大型項目 |