Vue3入口文件main.js解析

python 复制代码
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import ElementPlus from "element-plus";
import "element-plus/dist/index.css";
import * as ElementPlusIconsVue from "@element-plus/icons-vue";
import zhCn from "element-plus/dist/locale/zh-cn.mjs";

const app = createApp(App);

// 注册所有图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component);
}

app.use(store);
app.use(router);
app.use(ElementPlus, {
  locale: zhCn,
});

app.mount("#app");

这是一个 Vue 3 应用的主入口文件,我来详细分析每个部分:

1. 导入依赖模块

javascript 复制代码
import { createApp } from "vue";
  • 从 Vue 3 导入 createApp 函数,这是 Vue 3 创建应用实例的新方式
  • 相比 Vue 2 的 new Vue(),Vue 3 使用函数式创建方式
javascript 复制代码
import App from "./App.vue";
import router from "./router";
import store from "./store";
  • App.vue:根组件,整个应用的入口组件
  • router:Vue Router 路由配置,用于单页面应用的路由管理
  • store:Vuex 或 Pinia 状态管理器,用于全局状态管理
javascript 复制代码
import ElementPlus from "element-plus";
import "element-plus/dist/index.css";
import * as ElementPlusIconsVue from "@element-plus/icons-vue";
import zhCn from "element-plus/dist/locale/zh-cn.mjs";
  • ElementPlus:饿了么团队开发的 Vue 3 UI 组件库
  • CSS 样式文件:ElementPlus 的样式表
  • 图标库:ElementPlus 配套的图标组件集合
  • 中文语言包:将 ElementPlus 界面设置为中文

2. 创建应用实例

javascript 复制代码
const app = createApp(App);
  • 使用 createApp() 创建 Vue 应用实例
  • 传入根组件 App 作为参数

3. 批量注册图标组件

javascript 复制代码
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component);
}
  • 遍历 ElementPlus 图标库中的所有图标
  • 将每个图标作为全局组件注册到应用中
  • 注册后可以在任何组件中直接使用这些图标,如 <Edit />, <Delete />

4. 注册插件和中间件

javascript 复制代码
app.use(store);
app.use(router);
app.use(ElementPlus, {
  locale: zhCn,
});
  • app.use(store):注册状态管理器
  • app.use(router):注册路由系统
  • app.use(ElementPlus, { locale: zhCn }):注册 ElementPlus UI 库并配置为中文语言

5. 挂载应用

javascript 复制代码
app.mount("#app");
  • 将 Vue 应用挂载到 HTML 中 id 为 "app" 的 DOM 元素上
  • 通常对应 index.html 中的 <div id="app"></div>
  1. 组件化开发 :使用 .vue 单文件组件
  2. 路由管理:集成 Vue Router 进行页面导航
  3. 状态管理:使用 Vuex/Pinia 管理全局状态
  4. UI 框架:采用 ElementPlus 提供丰富的 UI 组件
  5. 国际化:配置中文语言包
  6. 图标系统:全局注册图标组件库
相关推荐
gyx_这个杀手不太冷静5 小时前
Agent开发进阶指南(第 1 章):AI Agent 到底是什么?
前端·agent·ai编程
小小小小宇6 小时前
模型相关知识
前端
小小小小宇6 小时前
模型相关知识二
前端
IT_陈寒6 小时前
Python装饰器竟然偷偷改了函数名?这个坑我爬了三天
前端·人工智能·后端
free356 小时前
作用域链与 Environment:变量查找、遮蔽和赋值怎么实现
javascript
Momo__7 小时前
Vite 8.1 打包开发模式——10000 组件冷启动 15 倍,"No Bundle Dev" 七年后被自己终结
前端·vue.js·vite
YHL7 小时前
🤖 Agent 智能体开发实战 · 第一课:Tool Use —— 让大模型自动干活
前端·javascript·人工智能
Monki7 小时前
AI 规范式 UI 设计,一键批量出页,高效落地不翻车
前端
山河木马7 小时前
渲染管线-计算得到gl_FragColor(片元着色器)之后续GPU流程
前端·webgl·计算机图形学
不想说话的麋鹿7 小时前
「项目实战」我用 Codex + GPT-5.5 + Trellis "氛围编程",独立做了一个情侣厨房小程序
前端·agent·全栈