element-plus快速上手教程
2025年12月25日大约 9 分钟约 2680 字
教程介绍
本教程是基于vite8,使用vue官方初始模板,逐步搭建一个完整的中后台管理系统框架。
使用vite初始化项目
cd E:/project/
# 使用create-vue创建项目
# pnpm create vue@latest -- --help # 帮助文档
pnpm create vue@latest vue-admin-template
pnpm add -D vite@8.0.0-beta.5 # 更新vite为8版本。 (`-D`安装到开发依赖区域)
cd vue-admin-template
pnpm installpackage.json是Node.js的配置文件,用来存放项目配置。- vite项目编译入口文件为
index.html里面的script标签内容。 pnpm create vue: 运行create-vue包,pnpm会自动给包名添加前缀create字段,所以注意这里不是在使用vue包。而业界共识create开头的包一般用初始化项目使用。
选择
TypeScriptJSX支持RouterPiniaOxlintrolldown选择使用示例代码来初始化项目
安装
axios: 点击查看安装
iconify图标安装
VueUse工具包: 安装查看
安装相关包
# 安装 element-plus 图标
npm install @element-plus/icons-vue
npm install -D unplugin-icons
# 安装pinia
npm install pinia-plugin-persist # 数据持久化插件- elementPlus图标 官方安装教程:点击查看
vite项目配置文件优化
vite.config.ts
import path from 'path'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import Icons from 'unplugin-icons/vite'
import IconsResolver from 'unplugin-icons/resolver'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import Inspect from 'vite-plugin-inspect'
const pathSrc = path.resolve(__dirname, 'src')
// https://vitejs.dev/config/
export default defineConfig({
base: './', // 打包后的文件引用使用相对路径(需要时可选)
resolve: {
alias: { '@': pathSrc, },
},
plugins: [
vue(),
AutoImport({
imports: ['vue'], // 自动导入Vue相关函数
resolvers: [
ElementPlusResolver(), // 自动导入Element Plus相关函数,如:ref,reactive,toRef等
IconsResolver({prefix: 'Icon',}), // 自动导入图标组件
],
dts: path.resolve(pathSrc, 'auto-imports.d.ts'),
}),
Components({
resolvers: [
ElementPlusResolver(), // 自动导入ElementPlus组件,如:ELMessage,ELMessageBox等
IconsResolver({ enabledCollections: ['ep'], }) // 自动注册图标组件
],
dts: path.resolve(pathSrc, 'components.d.ts'),
}),
Icons({ autoInstall: true, }),
Inspect(), // 安装Inspect插件
],
server: {
port: 8080, // 启动端口
open: false, // 启动后在浏览器打开
}
})
vite-plugin-inspect插件说明:点击查看
tsconfig.json
{
"compilerOptions": {
// ...
"allowJs": true,
// 配置路径别名(这里配置可以方便的在vscode中点击跳转到通过'@'导入的子页面;与项目启动无关)
"baseUrl": ".",
"paths": {"@/*": ["src/*"]}
}
// "exclude": ["dist", "node_modules"],
// "include": ["src/**/*"]
}src目录文件优化
src/main.ts
// 该文件会被父目录的index.html页面调用起来
import { createApp } from 'vue'
import App from './App.vue'
import pinia from './store/index.js'
import router from './router'
import './style.css'
import './permission.js'
// 使用App.vue组件创建一个应用
const app = createApp(App)
// 在vue app中安装路由插件
app.use(router)
// 在vue app中全局注册状态管理插件
app.use(pinia)
// 将应用挂载到index.html的id为app的标签上
app.mount('#app')src/App.vue
<script setup lang="ts"></script>
<template>
<router-view></router-view>
</template>
<style lang="scss" scoped></style>- 删除
src/components/HelloWorld.vue示例组件
关于目录结构:
src/main.js入口文件src/App.vue项目根组件,一级路由出口src/assets/静态资源src/components/可复用的通用业务组件
其他常用目录结构:
src/views/页面组件。对应路由表,以页面的形式展示src/api/接口请求src/router/路由src/store/全局状态src/styles/全局样式src/utils/工具模块src/libs/通用非业务的组件库(与项目解耦,可用于其他项目)src/constants/常量src/directives自定义指令src/vendor/外部供应资源。比如:人类行为认证src/permission.js页面权限控制src/assets/icons/页面图标src/assets/images/页面图片
全局样式优化
在main.ts中已经默认引用了style.css全局样式表,所以做一些扩展就行。下面仅做一些样式演示而已
src/style.css
/* 导入 tailwind 的基础指令组件 */
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
font-family: Inter, Avenir, Helvetica, Arial, sans-serif;
font-size: 16px;
line-height: 24px;
font-weight: 400;
box-sizing: content-box;
color-scheme: light dark;
color: rgba(255, 255, 255, 0.87);
background-color: #242424;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-text-size-adjust: 100%;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
body {
margin: 0;
/* display: flex; */
/* place-items: center; */
min-width: 320px;
min-height: 100vh;
}
h1 {
font-size: 3.2em;
}
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
background-color: #1a1a1a;
cursor: pointer;
transition: border-color 0.25s;
}
button:hover {
border-color: #646cff;
}
button:focus,
button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}
.card {
padding: 2em;
}
/* #app {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
} */
@media (prefers-color-scheme: light) {
:root {
color: #213547;
background-color: #ffffff;
}
a:hover {
color: #747bff;
}
button {
background-color: #f9f9f9;
}
}
/* ------------------- element-plus css ---------------- */
/* 处理Avatar头像组件的背景透明问题 */
/* 这里似乎没有应用上去 */
.el-avatar {
--el-avatar-bg-color: none;
--el-avatar-background-color: none;
}
/** --------- 其他技巧演示 ---------- */
/** 定义通用css */
/**
@mixin relative {
position: relative;
width: 100%;
height: 100%;
}
@mixin clearfix {
&:after {
content: '';
display: table;
clear: both;
}
}
*/
/** 定义常量 */
/**
$menuBg: #304156;
$sideBarWidth: 210px;
*/
/** 导出常量 */
/**
// https://www.bluematador.com/blog/how-to-share-variables-between-js-and-sass
// JS 与 scss 共享变量,在 scss 中通过 :export 进行导出,在 js 中可通过 ESM 进行导入
:export {
menuBg: $menuBg;
sideBarWidth: $sideBarWidth;
}
*/
/** 导入其他样式表 */
/**
@import './styles/variables.scss';
@import './styles/mixin.scss';
*/可以清除掉默认的
#app的样式
环境变量配置
在vite中提供了.env文件,默认提供了四种固定文件格式:
.env # 所有情况下都会加载
.env.local # 所有情况下都会加载,但会被 git 忽略
.env.[mode] # 只在指定模式下加载
.env.[mode].local # 只在指定模式下加载,但会被 git 忽略.env.development
# 开发时加载的环境变量
# 只在指定模式(development)下加载
# 只有以 VITE_ 为前缀的变量才会暴露给经过 vite 处理
NODE_ENV=development
VITE_APP_BASE_URL=/local_api # 本地跨域代理
# VITE_APP_BASE_URL=https://api.imooc-admin.lgdsunday.club/api
# 请注意该文件是放在项目根目录中,不是放在src目录下.env.production
# 正式环境加载的环境变量
# 只在指定模式(production)下加载
# base api, 只有以 VITE_ 为前缀的变量才会暴露给经过 vite 处理测试:
console.log(import.meta.env.VITE_APP_BASE_URL)
配置 tailwindcss
shell
# 安装 tailwindcss
npm install -D tailwindcss@latest autoprefixer@latest
# 创建 tailwind.config.js 配置文件
npx tailwindcss init -ptailwind.config.cjs
/** @type {import('tailwindcss').Config} */
module.exports = {
// Tailwind 应用范围
content: ['./index.html', './src/**/*.{vue,js}'],
theme: {
extend: {
transitionProperty: {
'w': 'width',
'ml': 'margin-left'
}
},
},
plugins: [],
// prefix: 'tw-', // 如果class名有冲突可以加个自定义前缀
}src/style.css
/* 导入 tailwind 的基础指令组件 */
@tailwind base;
@tailwind components;
@tailwind utilities;
/* 请在 src/main.ts 中默认会引用该文件: import './style.css' */- tailwindcss官方英文文档:点击查看 v3.1.8
- tailwindcss中文文档:点击查看 v2.2.16
- vscode中安装
Tailwind CSS IntelliSense插件用来代码补全 - vite2.0默认支持
postcss,无需安装postcss预处理 - autoprefixer会给css加上不同的浏览器前缀来提高兼容性
本章总结
教程到此还无法正常启动项目,因为有一些依赖文件还没有创建。
依赖文件有:
- src/store/index.js
- src/router/index.ts
- src/permission.js
请继续看下一章
其他包安装
安装Bootstrap
shell
npm i --save bootstrap @popperjs/core
npm i --save-dev sasssrc/main.ts
import "bootstrap"
import "bootstrap/dist/css/bootstrap.min.css"- Bootstrap官方安装教程:点击查看
安装electron
npm install -D electron
npm install -D electron-builder # 打包工具
npm install -D electron-devtools-installer # 开发调试
npm install -D vite-plugin-electron # node+electron api
npm install -D rimraf # 辅助作用,快速删除某些文件
# 后续配置参考 https://juejin.cn/post/7102681636096966687vite-plugin-electron: Github
安装animate.css
shell
npm install animate.css --savesrc/main.ts
在需要用到的vue界面中import 'animate.css'局部引入或者在main.js中全局引入
import animate from 'animate.css'
app.use(animate)单独使用
使用时给html标签添加类名后便有动画效果:
<div class="animate__animated animate__fadeIn">内容部分</div>
<h1 class="animated infinite bounce delay-2s faster">Example</h1>
animate__animated是固定写法
结合路由使用
把router-view包装起来,当路由跳转展示出来的页面就会有动画效果,显得不会太生硬
<transition
enter-active-class="animate__animated animate__lightSpeedInRight"
leave-active-class="animate__animated animate__lightSpeedOutRight"
>
<router-view />
</transition>官网:点击查看
安装 three.js
npm install three
npm install three-orbit-controls # 轨道控件
npm i --save three-obj-mtl-loader # 加载.obj和.mtl文件的插件
npm i --save three-css2drender # 渲染器插件
# 在页面中导入 import * as Three from 'three'官网:点击查看 语法补全参看:https://blog.csdn.net/xieweiaaa/article/details/123878649
安装 socket.io
websocket协议客户端服务器工具
shell
npm install vue-socket.io socket.io-clientsrc/main.js
import VueSocketIO from 'vue-socket.io'
import SocketIO from 'socket.io-client'
Vue.use(new VueSocketIO({
debug: true,
connection: SocketIO('ws://127.0.0.1:3000'), // 连接后端地址
}))安装echarts
shell
npm install echarts --save页面使用
<template>
<div class="echarts-box">
<div id="main" :style="{ width: '900px', height: '300px' }"></div>
</div>
</template>
<script setup>
import * as echarts from 'echarts'
let myChart = echarts.init(document.getElementById('main'))
myChart.setOption({
xAxis:{},
yAxis:{},
series:[]
})
</script>vite社区模板
# 通过社区模板初始化项目
npx degit lin-xin/vue-manage-system#master vue3-admin-template
npx degit xiaoxian521/vue-pure-admin#main vue3-admin-template
npx degit hooray/fantastic-admin#master vue3-admin-template
npx degit hooray/fantastic-admin#example vue3-admim-example-template
npx degit fantastic-admin/pro#master vue3-admin-template
npx degit fantastic-admin/pro#example vue3-admin-example-template
npx degit chuzhixin/vue-admin-better#master vue3-admin-template
cd vue3-admin-template
pnpm install
pnpm run dev- vite社区模板列表:点击查看
- Fantastic-admin官方文档:点击查看
- vue-manage-system:点击查看
- vue-pure-admin官方文档:点击查看
- vue-admin-better官方文档:点击查看
vscode调试
- 打断点
- vscode侧边栏点击
运行和调试,绿色箭头右边下拉菜单选择添加配置,选择Edge:启动 - 在终端启动项目:
npm run dev - 点击绿色小箭头开启调试
注意调试端口和启动端口要一致
项目命名规范
文件命名规范:
- 项目根目录和子目录都使用
中划线区分单词来命名 - 项目的vue组件文件名使用首字母大写的驼峰式命名
- 项目的其他文件所有文件(包括vue页面)使用首字母小写的驼峰式命名
- 文件名尽量使用名词开头,后面再加动词,因为vscode文件排序是按字母排序的,类似的文件可以排在一起
变量命名规范:
- vue组件变量使用首字母大写的驼峰式命名
- 普通变量使用首字母小写的驼峰式命名