介绍

Element Plus,一套为开发者、设计师和产品经理准备的基于 Vue 3.0 的桌面端组件库:

  • 相信很多同学在Vue2中都使用过element-ui,而element-plus正是element-ui针对于vue3开发的一个UI组件库;
  • 它的使用方式和很多其他的组件库是一样的,所以学会element-plus,其他类似于ant-design-vue、NaiveUI、VantUI都是差不多的;

安装

  1. npm install element-plus

引入使用

全局引入

一种引入element-plus的方式是全局引入,代表的含义是所有的组件和插件都会被自动注册,直接用,不需要import引入、不需要components注册:

  1. // /src/main.js
  2. // 1、引入
  3. import ElementPlus from 'element-plus'
  4. // 2、引入样式
  5. import 'element-plus/lib/theme-chalk/index.css'
  6. import router from './router'
  7. import store from './store'
  8. createApp(App).use(router).use(store).use(ElementPlus).mount('#app')

image.png

优点:使用比较简单
缺点:全部组件不管用没用上,都会打包,打包后体积可能会有点大

局部引入

也就是在开发中用到某个组件对某个组件进行引入:

  1. <template>
  2. <div id="app">
  3. <router-link to="/login">登录</router-link>
  4. <router-link to="/main">首页</router-link>
  5. <router-view></router-view>
  6. <h2>{{ $store.state.name }}</h2>
  7. <el-button>默认按钮</el-button>
  8. <el-button type="primary">主要按钮</el-button>
  9. <el-button type="success">成功按钮</el-button>
  10. <el-button type="info">信息按钮</el-button>
  11. <el-button type="warning">警告按钮</el-button>
  12. <el-button type="danger">危险按钮</el-button>
  13. </div>
  14. </template>
  15. <script lang="ts">
  16. import { defineComponent } from 'vue'
  17. // 1、引入
  18. import { ElButton } from 'element-plus'
  19. export default defineComponent({
  20. name: 'App',
  21. components: {
  22. // 2、注册
  23. ElButton
  24. }
  25. })
  26. </script>
  27. <style lang="less">
  28. </style>

优点:打包后体积会小些
缺点:引用起来麻烦些

局部注册:样式问题

但是我们会发现是没有对应的样式的,引入样式有3种方式:

1、全局引用样式

(像之前做的那样),但是没使用的组件的样式也拿进来了;

2、局部引用样式

就是麻烦点,还要去找css的名字
image.png

3、局部引用样式(通过babel的插件)

好处是也是局部引入,但是不需要写import 样式了,babel会自动帮我们引入对应的样式

1.安装babel的插件:

  1. npm install babel-plugin-import -D

2.配置/src/babel.config.js

  1. module.exports = {
  2. plugins: [
  3. [
  4. 'import',
  5. {
  6. libraryName: 'element-plus',
  7. customStyleName: (name) => {
  8. return `element-plus/lib/theme-chalk/${name}.css`
  9. }
  10. }
  11. ]
  12. ],
  13. presets: ['@vue/cli-plugin-babel/preset']
  14. }

image.png 但是公共基础的样式不会引入,还是要写到全局main.js里面

但是这里依然有个弊端:

  • 这些组件我们在多个页面或者组件中使用的时候,都需要导入并且在components中进行注册;
  • 所以我们可以将它们在全局注册一次;
  1. import {
  2. ElButton,
  3. ElTable,
  4. ElAlert,
  5. ElAside,
  6. ElAutocomplete,
  7. ElAvatar,
  8. ElBacktop,
  9. ElBadge,
  10. } from 'element-plus'
  11. const app = createApp(App)
  12. const components = [
  13. ElButton,
  14. ElTable,
  15. ElAlert,
  16. ElAside,
  17. ElAutocomplete,
  18. ElAvatar,
  19. ElBacktop,
  20. ElBadge
  21. ]
  22. for (const cpn of components) {
  23. app.component(cpn.name, cpn)
  24. }

main.js (main.ts)显得比较乱,可以考虑把ui组件相关的封装一个函数到外面文件,这里只需要引入即可。
image.png
image.png
image.png