elementui npm
安装 Element UI 的步骤
使用 npm 安装 Element UI 是最常见的方式,适用于基于 Vue.js 的项目。
npm install element-ui -S
安装完成后,可以在项目的 package.json 文件中看到 Element UI 的依赖项。
引入 Element UI
在 Vue 项目中引入 Element UI 有两种方式:完整引入和按需引入。
完整引入
在项目的入口文件(通常是 main.js 或 main.ts)中添加以下代码:
import Vue from 'vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import App from './App.vue';
Vue.use(ElementUI);
new Vue({
el: '#app',
render: h => h(App)
});
按需引入 如果需要优化项目体积,可以使用按需引入的方式。首先安装 babel-plugin-component:

npm install babel-plugin-component -D
然后在 babel.config.js 中配置插件:
module.exports = {
presets: ['@vue/cli-plugin-babel/preset'],
plugins: [
[
'component',
{
libraryName: 'element-ui',
styleLibraryName: 'theme-chalk'
}
]
]
};
之后在需要使用的组件中单独引入:
import { Button, Select } from 'element-ui';
import 'element-ui/lib/theme-chalk/button.css';
import 'element-ui/lib/theme-chalk/select.css';
Vue.component(Button.name, Button);
Vue.component(Select.name, Select);
使用 Element UI 组件
安装并引入后,可以直接在 Vue 组件中使用 Element UI 的组件。例如,使用一个按钮:

<template>
<el-button type="primary">主要按钮</el-button>
</template>
主题定制
Element UI 支持主题定制。可以通过安装主题生成工具来定制主题:
npm install element-theme -g
npm install element-theme-chalk -D
初始化变量文件:
et -i
编辑生成的 element-variables.scss 文件,然后编译主题:
et
编译完成后,将生成的 theme 文件夹中的内容替换原来的 CSS 文件即可。
注意事项
- 确保项目中已安装 Vue.js,Element UI 依赖于 Vue。
- 按需引入时,每个组件的样式文件需要单独引入,否则组件可能无法正常显示。
- 主题定制需要额外的工具支持,确保按照官方文档操作。






