image
什么是elementUI
ElementUI是餓了么前端團(tuán)隊(duì)推出的一款基于Vue.js 2.0 的桌面端UI框架
大白話: 和Bootstrap一樣對(duì)原生的HTML標(biāo)簽進(jìn)行了封裝, 讓我們能夠?qū)W⒂跇I(yè)務(wù)邏輯而不是UI界面
elementUI的使用
1. 安裝 elementUI
npm i element-ui -S
2. 導(dǎo)入框架和css文件
在 main.js 中寫入以下內(nèi)容:
import Vue from 'vue'
import App from './App.vue'
// 導(dǎo)入elementUI和elementUI的CSS文件
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
// 告訴Vue, 我們需要在項(xiàng)目中使用elementUI
Vue.use(ElementUI)
new Vue({
render: h => h(App)
}).$mount('#app')
3. 使用組件
在elementUI官方文檔中找到需要的組件悍及,將代碼復(fù)制到需要的地方
例如:我復(fù)制了一段Button按鈕和Switch的代碼到App.vue組件中
App.vue
<template>
<div id="app">
<el-row>
<el-button>默認(rèn)按鈕</el-button>
<el-button type="primary">主要按鈕</el-button>
<el-button type="success">成功按鈕</el-button>
<el-button type="info">信息按鈕</el-button>
<el-button type="warning">警告按鈕</el-button>
<el-button type="danger">危險(xiǎn)按鈕</el-button>
</el-row>
<el-switch
v-model="value"
active-color="#13ce66"
inactive-color="#ff4949">
</el-switch>
</div>
</template>
運(yùn)行npm run serve
指令后就可以在瀏覽器看到效果了
image
elementUI 優(yōu)化
默認(rèn)情況下無(wú)論我們有沒(méi)有使用到某個(gè)組件, 在打包的時(shí)候都會(huì)將elementUI中所有的組件打包到我們的項(xiàng)目中
這樣就導(dǎo)致了我們的項(xiàng)目體積比較大,用戶訪問(wèn)比較慢
如何優(yōu)化
為了解決這個(gè)問(wèn)題,elementUI推出了按需導(dǎo)入钦睡,按需打包由蘑,也就是只會(huì)將我們用到的組件打包到了我們的項(xiàng)目中
沒(méi)有用到的不會(huì)被打包
參考文檔
1. 安裝 babel-plugin-component
npm install babel-plugin-component -D
2. 修改babel.config.js配置文件
module.exports = {
presets: [
['@vue/cli-plugin-babel/preset', { modules: false }]
],
plugins: [
[
'component',
{
libraryName: 'element-ui',
styleLibraryName: 'theme-chalk'
}
]
]
}
3. 按需導(dǎo)入組件
比如我只用到了 Button 和 Switch部凑,那么需要在 main.js 中寫入以下內(nèi)容:
import Vue from 'vue'
import App from './App.vue'
// 導(dǎo)入需要的組件
import { Button, Switch } from 'element-ui'
// 告訴Vue, 需要在項(xiàng)目中使用哪些組件
Vue.component(Button.name, Button)
Vue.component(Switch.name, Switch)
/* 或?qū)憺? * Vue.use(Button)
* Vue.use(Switch)
*/
new Vue({
render: h => h(App)
}).$mount('#app')
運(yùn)行npm run serve
指令后依然可以在瀏覽器看到效果
image