介绍
Element Plus,一套为开发者、设计师和产品经理准备的基于 Vue 3.0 的桌面端组件库:
- 相信很多同学在Vue2中都使用过element-ui,而element-plus正是element-ui针对于vue3开发的一个UI组件库;
- 它的使用方式和很多其他的组件库是一样的,所以学会element-plus,其他类似于ant-design-vue、NaiveUI、VantUI都是差不多的;
安装
npm install element-plus
引入使用
全局引入
一种引入element-plus的方式是全局引入,代表的含义是所有的组件和插件都会被自动注册,直接用,不需要import引入、不需要components注册:
// /src/main.js// 1、引入import ElementPlus from 'element-plus'// 2、引入样式import 'element-plus/lib/theme-chalk/index.css'import router from './router'import store from './store'createApp(App).use(router).use(store).use(ElementPlus).mount('#app')

优点:使用比较简单
缺点:全部组件不管用没用上,都会打包,打包后体积可能会有点大
局部引入
也就是在开发中用到某个组件对某个组件进行引入:
<template><div id="app"><router-link to="/login">登录</router-link><router-link to="/main">首页</router-link><router-view></router-view><h2>{{ $store.state.name }}</h2><el-button>默认按钮</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">危险按钮</el-button></div></template><script lang="ts">import { defineComponent } from 'vue'// 1、引入import { ElButton } from 'element-plus'export default defineComponent({name: 'App',components: {// 2、注册ElButton}})</script><style lang="less"></style>
优点:打包后体积会小些
缺点:引用起来麻烦些
局部注册:样式问题
但是我们会发现是没有对应的样式的,引入样式有3种方式:
1、全局引用样式
(像之前做的那样),但是没使用的组件的样式也拿进来了;
2、局部引用样式
就是麻烦点,还要去找css的名字
3、局部引用样式(通过babel的插件)
好处是也是局部引入,但是不需要写import 样式了,babel会自动帮我们引入对应的样式
1.安装babel的插件:
npm install babel-plugin-import -D
2.配置/src/babel.config.js
module.exports = {plugins: [['import',{libraryName: 'element-plus',customStyleName: (name) => {return `element-plus/lib/theme-chalk/${name}.css`}}]],presets: ['@vue/cli-plugin-babel/preset']}
但是公共基础的样式不会引入,还是要写到全局main.js里面
但是这里依然有个弊端:
- 这些组件我们在多个页面或者组件中使用的时候,都需要导入并且在components中进行注册;
- 所以我们可以将它们在全局注册一次;
import {ElButton,ElTable,ElAlert,ElAside,ElAutocomplete,ElAvatar,ElBacktop,ElBadge,} from 'element-plus'const app = createApp(App)const components = [ElButton,ElTable,ElAlert,ElAside,ElAutocomplete,ElAvatar,ElBacktop,ElBadge]for (const cpn of components) {app.component(cpn.name, cpn)}
main.js (main.ts)显得比较乱,可以考虑把ui组件相关的封装一个函数到外面文件,这里只需要引入即可。


