下包
yarn add element-ui
引入全局样式
import Element from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(Element);
显示正常
工作中推荐局部引入,会减少代码体积
### 按需导入 (推荐)
减轻将来打包后的包的体积
- 安装
```jsx
yarn add element-ui
```
- 安装`babel-plugin-component`
```jsx
yarn add babel-plugin-component -D
```
- 在` babel.config.js `中配置
```jsx
module.exports = {
presets: [
'@vue/cli-plugin-babel/preset'
],
// 新增plugins插件节点,修改完配置文件一定重启项目
"plugins": [
[
"component",
{
"libraryName": "element-ui",
"styleLibraryName": "theme-chalk"
}
]
]
}
```
- 使用插件`main.js`中
```jsx
import { Button } from 'element-ui'
Vue.use(Button)
```
### 抽离element.js模块
- 由于组件的导入都书写到了`main.js`中,导致`main.js` 代码冗余
将element-ui组件的导入和注册单独抽离到utils文件夹中
- 新建element.js
- **项目中 ** 完整按需导入如下:
```jsx
import Vue from 'vue';
import {
Popconfirm,
Avatar,
Breadcrumb,
BreadcrumbItem,
Pagination,
Dialog,
Menu,
Input,
Option,
Button,
Table,
TableColumn,
Form,
FormItem,
Icon,
Row,
Col,
Card,
Container,
Header,
Aside,
Main,
Footer,
Link,
Image,
Loading,
MessageBox,
Message,
Drawer,
MenuItem
} from 'element-ui';
Vue.use(Breadcrumb);
Vue.use(BreadcrumbItem);
Vue.use(Drawer);
Vue.use(Popconfirm);
Vue.use(Avatar);
Vue.use(Pagination);
Vue.use(Dialog);
Vue.use(Menu);
Vue.use(MenuItem);
Vue.use(Input);
Vue.use(Option);
Vue.use(Button);
Vue.use(Table);
Vue.use(TableColumn);
Vue.use(Form);
Vue.use(FormItem);
Vue.use(Icon);
Vue.use(Row);
Vue.use(Col);
Vue.use(Card);
Vue.use(Container);
Vue.use(Header);
Vue.use(Aside);
Vue.use(Main);
Vue.use(Footer);
Vue.use(Link);
Vue.use(Image);
Vue.use(Loading.directive);
Vue.prototype.$loading = Loading.service;
Vue.prototype.$msgbox = MessageBox;
Vue.prototype.$alert = MessageBox.alert;
Vue.prototype.$confirm = MessageBox.confirm;
Vue.prototype.$prompt = MessageBox.prompt;
Vue.prototype.$notify = Notification;
Vue.prototype.$message = Message;
```
- 直接导入main.js中
```jsx
// 直接导入vant-ui.js
import '@/utils/element.js'
```