Element Plus 是饿了么团队开源的一套基于 Vue 3 的桌面端组件库,专为快速构建现代化中后台管理系统而设计。本教程将带你从零开始,全面掌握 Element Plus 的安装、配置与使用。
一、Element Plus 简介
Element Plus 是 Element UI 的 Vue 3 版本,提供了丰富的 UI 组件和良好的开发体验:
主要特性:
- 🧩 丰富组件:包含表单、表格、弹窗、导航、布局等常用 UI 组件
- 🌞 暗黑模式:内置支持深色主题
- 🧊 开箱即用:支持自动导入功能,简化开发流程
- 🔤 多语言支持:官方提供中英文语言包,轻松实现国际化
- 🛠️ TypeScript 友好:原生支持类型推导,提供完善的类型定义
二、环境准备与安装
1. 创建 Vue 3 项目
推荐使用 Vite 创建项目(最快的方式):
bash
npm create vite@latest my-element-app --template vue-ts
cd my-element-app
npm install
或者使用 Vue CLI(传统方式):
bash
npm install -g @vue/cli
vue create my-element-app
# 选择 Vue 3 配置
cd my-element-app
2. 安装 Element Plus
bash
npm install element-plus --save
或者使用 yarn/pnpm:
bash
yarn add element-plus
# 或
pnpm install element-plus
三、配置 Element Plus
方式一:全局引入(推荐新手)
适合场景:小型项目或快速原型开发,简单直接
修改 main.ts
或 main.js
:
javascript
// src/main.ts
import { createApp } from 'vue'
import App from './App.vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
// 中文语言包(可选)
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
const app = createApp(App)
// 使用Element Plus并设置中文
app.use(ElementPlus, {
locale: zhCn, // 设置中文
})
// 全局注册所有组件
app.mount('#app')
方式二:按需导入(推荐生产环境)
适合场景:中大型项目,需要优化打包体积
1. 安装必要插件
npm install -D unplugin-vue-components unplugin-auto-import
2. 配置 vite.config.ts
javascript
// vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
export default defineConfig({
plugins: [
vue(),
AutoImport({
resolvers: [ElementPlusResolver()],
}),
Components({
resolvers: [ElementPlusResolver()],
}),
],
})
优势:无需手动导入组件,直接在模板中使用,打包体积更小
可选配置:图标全局注册
如果需要使用 Element Plus 的图标:
javascript
// 在 main.ts 中添加
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
const app = createApp(App)
// 全局注册所有图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
app.component(key, component)
}
app.use(ElementPlus)
app.mount('#app')
四、快速开始:第一个 Element Plus 应用
基础按钮示例
创建一个简单的组件来测试 Element Plus 是否正常工作:
TypeScript
<!-- src/components/HelloElementPlus.vue -->
<template>
<div class="hello-element">
<h2>Element Plus 快速开始</h2>
<!-- 基础按钮 -->
<el-row class="mb-4">
<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>
</el-row>
<!-- 带图标的按钮 -->
<el-row class="mb-4">
<el-button type="primary" :icon="Edit">编辑</el-button>
<el-button type="success" :icon="Check">保存</el-button>
<el-button type="danger" :icon="Delete">删除</el-button>
</el-row>
<!-- 表单示例 -->
<el-form :model="form" class="demo-form" label-width="80px">
<el-form-item label="用户名">
<el-input v-model="form.username" placeholder="请输入用户名"></el-input>
</el-form-item>
<el-form-item label="密码">
<el-input v-model="form.password" type="password" placeholder="请输入密码"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="onSubmit">提交</el-button>
<el-button @click="onReset">重置</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script setup lang="ts">
import { reactive } from 'vue'
import { ElMessage } from 'element-plus'
// 如果按需引入图标,需要单独导入
// import { Edit, Check, Delete } from '@element-plus/icons-vue'
// 定义表单数据
const form = reactive({
username: '',
password: ''
})
// 提交表单
const onSubmit = () => {
if (!form.username || !form.password) {
ElMessage.warning('请填写完整信息')
return
}
ElMessage.success(`欢迎 ${form.username}!`)
}
// 重置表单
const onReset = () => {
form.username = ''
form.password = ''
ElMessage.info('表单已重置')
}
</script>
<style scoped>
.hello-element {
padding: 20px;
}
.mb-4 {
margin-bottom: 16px;
}
.demo-form {
max-width: 400px;
}
</style>
然后在 App.vue
中使用这个组件:
TypeScript
<!-- src/App.vue -->
<template>
<div id="app">
<HelloElementPlus />
</div>
</template>
<script setup lang="ts">
import HelloElementPlus from './components/HelloElementPlus.vue'
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
五、常用组件使用指南
1. 表单组件
TypeScript
<template>
<el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
<el-form-item label="活动名称" prop="name">
<el-input v-model="form.name" />
</el-form-item>
<el-form-item label="活动区域" prop="region">
<el-select v-model="form.region" placeholder="请选择活动区域">
<el-option label="区域一" value="shanghai" />
<el-option label="区域二" value="beijing" />
</el-select>
</el-form-item>
<el-form-item label="活动时间">
<el-col :span="11">
<el-date-picker
v-model="form.date1"
type="date"
placeholder="选择日期"
style="width: 100%"
/>
</el-col>
<el-col :span="2" class="text-center">-</el-col>
<el-col :span="11">
<el-time-picker
v-model="form.date2"
placeholder="选择时间"
style="width: 100%"
/>
</el-col>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm">立即创建</el-button>
<el-button @click="resetForm">重置</el-button>
</el-form-item>
</el-form>
</template>
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
const formRef = ref()
const form = reactive({
name: '',
region: '',
date1: '',
date2: ''
})
const rules = {
name: [
{ required: true, message: '请输入活动名称', trigger: 'blur' },
{ min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
],
region: [
{ required: true, message: '请选择活动区域', trigger: 'change' }
]
}
const submitForm = () => {
formRef.value.validate((valid) => {
if (valid) {
ElMessage.success('提交成功!')
} else {
ElMessage.error('请检查表单')
}
})
}
const resetForm = () => {
formRef.value.resetFields()
}
</script>
2. 数据展示组件
TypeScript
<template>
<div>
<!-- 表格 -->
<el-table :data="tableData" style="width: 100%">
<el-table-column prop="date" label="日期" width="180" />
<el-table-column prop="name" label="姓名" width="180" />
<el-table-column prop="address" label="地址" />
</el-table>
<!-- 卡片 -->
<el-row :gutter="20" class="mt-4">
<el-col :span="8" v-for="item in 3" :key="item">
<el-card :body-style="{ padding: '0px' }">
<img src="https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png" class="image">
<div style="padding: 14px;">
<span>好吃的汉堡</span>
<div class="bottom">
<time class="time">2025-01-01</time>
<el-button text class="button">操作按钮</el-button>
</div>
</div>
</el-card>
</el-col>
</el-row>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
const tableData = ref([
{
date: '2025-01-01',
name: '张三',
address: '上海市普陀区金沙江路 1518 弄'
},
{
date: '2025-01-02',
name: '李四',
address: '上海市普陀区金沙江路 1517 弄'
},
{
date: '2025-01-03',
name: '王五',
address: '上海市普陀区金沙江路 1519 弄'
}
])
</script>
<style scoped>
.image {
width: 100%;
display: block;
}
.bottom {
margin-top: 13px;
line-height: 12px;
display: flex;
justify-content: space-between;
align-items: center;
}
.button {
padding: 0;
float: right;
}
.time {
font-size: 13px;
color: #999;
}
.mt-4 {
margin-top: 16px;
}
</style>
六、进阶配置
1. 主题定制
Element Plus 支持通过 CSS 变量或 Sass 变量定制主题:
方法一:使用 CSS 变量(推荐)
在 src/style/element-variables.css
中:
TypeScript
:root {
--el-color-primary: #409eff;
--el-color-primary-light-3: #79bbff;
--el-color-primary-light-5: #a0cfff;
--el-color-primary-light-7: #c6e2ff;
--el-color-primary-light-8: #d9ecff;
--el-color-primary-light-9: #ecf5ff;
--el-color-primary-dark-2: #337ecc;
}
然后在 main.ts
中引入:
import './style/element-variables.css'
方法二:Sass 变量定制(更灵活)
- 安装 Sass:
npm install -D sass
- 创建
src/styles/element/index.scss
:
XML
// 覆盖主题色变量
$--color-primary: #2c82ff;
// 引入 Element Plus 样式
@use "element-plus/theme-chalk/src/index" as *;
- 在
vite.config.ts
中配置:
TypeScript
css: {
preprocessorOptions: {
scss: {
additionalData: `@use "@/styles/element/index.scss" as *;`,
},
},
}
2. 国际化配置
TypeScript
// main.ts
import { createApp } from 'vue'
import App from './App.vue'
import ElementPlus from 'element-plus'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import en from 'element-plus/dist/locale/en.mjs'
const app = createApp(App)
// 根据用户语言偏好设置
const userLanguage = navigator.language.startsWith('zh') ? zhCn : en
app.use(ElementPlus, {
locale: userLanguage,
})
app.mount('#app')
七、最佳实践
- 开发阶段:使用全局引入方式,快速开始开发
- 生产环境:使用按需引入方式,优化打包体积
- 组件组织:将常用的 Element Plus 组件封装成业务组件
- 表单处理:结合 Vue 3 的响应式系统和 Element Plus 的表单验证
- 主题管理:建立统一的设计规范,合理定制主题色彩
- 类型安全:充分利用 TypeScript 提供的类型提示和检查