行业知识
Vue2 引入使用ElementUI详解
2026-11-28 15:41:34
来源:互联网转载
目录
- 1 安装
- 2 引入
- 2.1 全局引入
- 2.1.1 引入
- 2.1.2 使用
- 2.2 按需引入
- 2.2.1 引入
- 2.2.2 使用
- 3 ���结
1 安装
推荐使用 npm 的方式安装,它能更好地和 webpack打包工具配合使用。(本项目使用安装方式)
npm i element-ui -S
也可以使用其他的包管理起进行安装:
# Yarn$ yarn add element-ui# pnpm$ pnpm install element-ui
2 引入
ElementUI分为全局引入和按需引入两种方式,一般在工程项目中,如果使用全局引入,则项目初始化时会导致不必要的资源加载,为提升项目性能,建议进行按需引入。以下我们对两种引入方式进行介绍。
2.1 全局引入
2.1.1 引入
在 main.js 中写入以下内容:
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)});2.1.2 使用
引入完成之后就可以使用组件了,如下示例为使用container组件和button组件:
效果如下:
代码如下:
Header Aside Main 按钮 Footer export default {};.el-header,.el-footer { background-color: #b3c0d1; color: #333; text-align: center; line-height: 60px;}.el-aside { background-color: #d3dce6; color: #333; text-align: center; line-height: 200px;}.el-main { background-color: #e9eef3; color: #333; text-align: center; line-height: 160px;}body > .el-container { margin-bottom: 40px;}.el-container:nth-child(5) .el-aside,.el-container:nth-child(6) .el-aside { line-height: 260px;}.el-container:nth-child(7) .el-aside { line-height: 320px;}2.2 按需引入
可以使用babel-plugin-component这个Babel插件。这样,你可以只引入你实际使用的组件和它们的样式,从而减小项目体积和构建时间。
2.2.1 引入
首先,安装 babel-plugin-component:
npm install babel-plugin-component -D
然后,将 .babelrc 或者babel.config.js文件修改为:
{ "presets": [["es2015", { "modules": false }]], "plugins": [ [ "component", { "libraryName": "element-ui", "styleLibraryName": "theme-chalk" } ] ]}2.2.2 使用
若想实现上图效果,按需引入时需要将使用的所有组件都引入进来,代码如下:
Header Aside Main 按钮 Footer import Vue from "vue";import { Button, Container, Header, Aside, Main, Footer } from "element-ui";Vue.use(Button);Vue.use(Container);Vue.use(Aside);Vue.use(Main);Vue.use(Footer);Vue.use(Header);export default {};.el-header,.el-footer { background-color: #b3c0d1; color: #333; text-align: center; line-height: 60px;}.el-aside { background-color: #d3dce6; color: #333; text-align: center; line-height: 200px;}.el-main { background-color: #e9eef3; color: #333; text-align: center; line-height: 160px;}body > .el-container { margin-bottom: 40px;}.el-container:nth-child(5) .el-aside,.el-container:nth-child(6) .el-aside { line-height: 260px;}.el-container:nth-child(7) .el-aside { line-height: 320px;}按需引入组件,组件全部名称详见官网;
3 总结
通常情况下,若是对性能没有要求时,可以使用全局导入方式引入所有组件,若对页面加载性能有要求,则最好使用按需加载方式引入组件,以防多余的资源加载增加页面初始化耗时。
下一篇:怎么去阿里云买服务器?