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. 图标系统:全局注册图标组件库
相关推荐
passerby60611 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了1 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅1 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅1 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅2 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment2 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅2 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊2 小时前
jwt介绍
前端
爱敲代码的小鱼2 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax
吹牛不交税3 小时前
admin.net-v2 框架使用笔记-netcore8.0/10.0版
vue.js·.netcore